Google Maps in Plain Vue

Matt Jenkins
May 6, 2017 · 2 min read

While building out some functionality involving Google Maps and Vue, I wanted to find a way to avoid dipping into the global scope for the Google Maps callback. The benefit of doing this, for me, was this component would now control when and where Google Maps and associated libraries would get loaded. Accomplishing this becomes as simple as using a promise and its resolve / reject functions to stay completely inside of Vue.

Since I wanted this component to trigger that download, it only made sense to have this be called on mounting the component. This would ensure that everything else was ready to receive the map; in this case, I wasn’t worried about destroying and re-mounting the component or having multiples of the component on a page.

Once the component has been mounted, we call createGoogleMaps() which is nothing more than a promise that creates the script and uses its onload and onerror to call the resolve or reject functions, respectively. Both of these functions are just simple Vue methods that can work with data that’s been loaded in already.

On success, we will see that we’re going to end up calling initGoogleMaps() which does exactly what one thinks it should do.

In my case, I’m grabbing my options object from Redux and do a few more initializations like setting up markers and event listeners. Depending on how your data is flowing into your component, you may end up having to utilize watching to trigger some map-related updates if your data isn’t immediately available.

The error message function works exactly the same way, but is much less interesting as we just use it as a way to alert the user to the issue and let them have some kind of feedback.


What’s great about this method is you’re now able to directly interact with Google Maps API as if you’re outside of Vue, but you gain all of the great niceties that Vue offers. This differs from something like the Vue 2 port of vue-google-maps where you’re accessing it in a more restricted way. If your end goal is just a simple map and a few pins then using a pre-built solution definitely would be an easier option.

Matt Jenkins

Written by

Developer that loves coding & designing

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade