This approach was further Improved after doing further research and troubleshooting.
https://dev.to/bawa93/troubleshooting-and-adding-google-maps-to-individual-nuxt-js-pages-1d34
Packages like vue2-google-maps and numerous others are available to use google maps in VueJs, But in my experience, those packages do not go well with Nuxtjs. and I am also of the thought that other packages or library should only be used when it's highly required.
These packages might help you in the short term but they are overkill in the long term as they have a lot of unnecessary abstraction.
What is a better approach?
I recommend using Google maps library directly and include that library only in those components where you will actually need it. There is a number of reasons for this approach.
- It will make sure heavy maps API code is loaded only where it is required.
- You have access to all the direct methods available on maps API
- You are keeping yours away from another open-source library. who know when the support for the open-source package you are using get ended :)
Here is how you can include Google maps Library in only those components where it is required.
pages/test.vue
<script>
const apiKey = process.env.GOOGLE_MAPS_API_KEY; // Package: @nuxtjs/dotenv
export default {
head() {
return {
script: [
{src: `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`}
]
};
},
methods: {
},
mounted() {
var input = this.$refs.searchTextField; //.getElementById('searchTextField');
new google.maps.places.Autocomplete(input);
},
data() {
return {};
}
};
</script>
<template>
<div>
<input class="input" ref="searchTextField" type="text">
</div>
</template>
That's all you have to do. If your app is heavily reliant on Google maps library you can edit the head section in nuxt.config.js.
Top comments (5)
Hey I'm having the same feature to implement in my project and I've made the same steps of you BUT I found that if I navigate to another page and then jump back into your component page this will lead you to this error (of course):
After a while I came into this solution:
what does this.googleAutocompleteInit do?
As far as I can remember something like this (see the code below).
A great post indeed
Great post it is