DEV Community

Lakh Bawa
Lakh Bawa

Posted on • Updated on

Troubleshooting and Adding Google Maps to individual Nuxt js pages

Update[New]: If you need simple Location Autocomplete, I have created new Gist: check this out and staff if find useful :) 
https://gist.github.com/lakhbawa/73409735265a5c48d48bc55c70e54993
```


I had a very hard time figuring out the best solution to add Google maps API into Nuxt js Project. It was because of several issues and the unique nature of Nuxt js.
My Goal was Simple
* Add google maps API only on those pages where it is being used.


# I tried varies techniques, and most of them were initiating some issues.
Some of the issues I was facing were.

* Script was being appended to the page as many times as the component was loaded.
* It was being hard to know when maps API was loaded.
* I simply didn't want to add maps API to all pages, which could be easily achieved by adding a script in nuxt.config.js

What were the techniques I tried?

1. I tried to use head() element of nuxt js page, which appends the scripts to head section of the page

Problem: 
- Every time component was loaded, it would append the script again to head section of the page, so the script was being appended multiple times in the page.
- It was also not working as expected when I would reload the page

2. Using packages https://www.npmjs.com/package/google-maps and https://www.npmjs.com/package/google-maps-api-loader, they were simply not working 

3. Vue2-google-maps - It was appending the maps API code to the whole codebase so increasing the overall page size.

What was it that worked.

I used mounted() hook of page component to the first check if google variable already exists (if yes, that means API is already loaded).




```
mounted() {
// if (!process.server) {
    if (typeof google === 'undefined') {
      const script = document.createElement('script')
      script.onload = this.onScriptLoaded
      script.type = 'text/javascript'
      script.src = `https://maps.googleapis.com/maps/api/js? 
      key=${apiKey}&libraries=places`
      document.head.appendChild(script)
    } else {
      this.onScriptLoaded()
    }

    // }

}
```


It would call onScriptLoaded() method.



```
methods: {

onScriptLoaded(event = null) {
// YOU HAVE ACCESS TO "new google" now, ADD YOUR GOOGLE MAPS FUNCTIONS HERE.

      // if (event) {
      //  console.log('Was added')
      // } else {
      //  console.log('Already existed')
      // }
 }
}
```



I hope it will save somebody's time. Thanks for reading and Have a good day.

Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
israelortuno profile image
Israel Ortuño • Edited

Consider using this library:

github.com/googlemaps/js-api-loader

    const loader = new Loader({
      apiKey: 'XXX',
      version: 'weekly',
      libraries: ['places']
    })

    await loader.load()

    this.placesAutocomplete = new window.google.maps.places.Autocomplete(this.$refs.place)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sixindustries profile image
Bryan

Extremely valuable post Lakh, thank you VERY much. Even with this critical info it still took me about 5 days to get exactly what my team was after which is basically a map with pre-populated markers (each with info window functionality) showing existing store locations in Texas but to also include a search feature with auto-complete that would also include info window functionality.

Probably sounds pretty basic, but it was a pretty sharp learning curve for me and quite frustrating at times. Without the snippet above, I would have been unable to even get off the ground much less work out my final solution for this maps project.

Thanks to you I got it done: habanerosvodka.com/buy

Thanks again!

Collapse
 
bawa_geek profile image
Lakh Bawa

you are welcome! Glad, i could be of help.

Collapse
 
drevantonder profile image
Andre van Tonder

Have a look at vue-meta.nuxtjs.org/api/#skip . I had the same issue where head() would add it multiple times. Using skip you can prevent it from being added twice.

Collapse
 
jessecogollo_2 profile image
Jesse cogollo

thank you, it's very useful to me 💪

Collapse
 
tomqsm profile image
Tomasz

Hi, thanks for sharing this, you saved me some headache and time :) best wishes.

Collapse
 
bawa_geek profile image
Lakh Bawa

Glad, I could be of help