Troubleshooting and Adding Google Maps to individual Nuxt js pages

bawa_geek

Lakh Bawa

Posted on May 11, 2020

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
πŸ’– πŸ’ͺ πŸ™… 🚩
bawa_geek
Lakh Bawa

Posted on May 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related