How To use Google Maps in Nuxt.js Project without Any package or heavy library

bawa_geek

Lakh Bawa

Posted on May 4, 2020

How To use Google Maps in Nuxt.js Project without Any package or heavy library

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>



Enter fullscreen mode Exit fullscreen mode

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
bawa_geek
Lakh Bawa

Posted on May 4, 2020

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

Sign up to receive the latest update from our blog.

Related