olefirenko / vue-google-autocomplete

A Vue.js autosuggest component for the Google Places API.
https://olefirenko.github.io/vue-google-autocomplete/
MIT License
505 stars 258 forks source link

Feature request: allow Google Maps API script to be loaded asynchronously #11

Open tinymachine opened 7 years ago

tinymachine commented 7 years ago

This component works great, but it would be even better if it could work when the Google Maps API script is loaded asynchronously.

Right now, if you set the API script to load asynchronously, the component can mount and run the mounted function before the script has fully loaded, throwing an error. I'm not that skilled a JS programming so I don't know how best to handle this, but an interesting idea using dynamic components was posted on the Laracasts forum in case that's helpful.

Thanks for sharing your work on this component, in any case -- it's a big help!

julienr-geronimo commented 7 years ago

Hello @tinymachine

On my side I have this

main.js

let g = document.createElement('script') 
g.type = 'text/javascript' 
g.onload = function () { 
    vue.$store.commit('GOOGLE_API_LOADED')
} 
g.src = 'https://maps.googleapis.com/maps/api/js?key=' + ỲOUR_KEY + '&libraries=places' 
g.async = true 
document.body.appendChild(g) 

So as you can see i commit something to the store

this something is :

store.js

export const GOOGLE_API_LOADED = (state) => {
    state.googleApiLoaded = true
}

And then when i used vue-google-autocomplete :

<vue-google-autocomplete v-if="$store.state.googleApiLoaded" id="search">

It may not be the best solution, but it's working :) !

sidouglas commented 7 years ago

Take a look at: https://stackoverflow.com/questions/1866717/document-createelementscript-adding-two-scripts-with-one-callback/1867135#1867135 You don't need to load it through your store.

frenchbread commented 7 years ago

+1

Thanks for sharing links. Current solution is not fully safe since API key is exposed in HTML file..

Update: just figured out that it's exposed in source code on site anyways.

syakirurahman commented 6 years ago

You can take a look at : https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8 for more simple solutions.

Just change the url with google maps api url