Vue 2 Tutorial- How To Implement And Show Google maps In A Vue Js App

Vue Js Google Map Integration Example; This Vue @ guide will make us learn how to integrate Google Maps into Vue 2 apps. We will also learn to add the simple functionality to search and add marker pins in Google Maps.

We will see the Google Map integration using the vue2-google-maps package.

We will be starting with just installing a simple new Vue app, adding a map plugin and then formulating the consent between Google Cloud and Vue Js.

Afterward, we will create a Google Map Component and register the component. We shall also be learning how to get the Google Map API key to display places on the map.

 

Vue Js Google Map Integration Tutorial

Let’s learn this implementation step by step:

Step 1- Install Vue Project

Step 2- Install Vue 2 Google Maps Library

Step 3- Get Google Maps API Key

Step 4- Register Vue Google Maps Module

Step 5- Create Vue Component

Step 6- Show Google Map

Step 7- Start Application

 

Step 1- Install Vue Project

First of all, we have to install a standard CLI tool for Vue Js development. We can easily do so since it’s available through the node package manager. We will have to do so using the below command:

npm install -g @vue/cli

 

Further, we have to run the command in order to install a new Vue app:

vue create vue-demo-app

 

Then, we move to the project root:

cd vue-demo-app

 

Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

 

To remove the above error for invoking the app, do remember to update the “scripts”: [] array in the package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

 

Step 2- Install Vue 2 Google Maps Library

Further, we have to run the provided command to add the Vue2 Google Maps package into the Vue app:

npm install vue2-google-maps

 

Step 3- Get Google Maps API Key

We need to get the Google Maps API key in order to add the Google Maps in Vue. See the below instructions that are to be followed for doing so:

  1. Go to Google Cloud Platform.
  2. Then, we create a new project. Look at the top left section and click the project dropdown.
  3. Do remember to click on the APIs & Services > Credentials at the left vertical menu.
  4. Afterward, we have to click on Create Credentials, then on the API key.
  5. Thereafter, we need to copy the API key from the model dialog that has just appeared on our screen.
  6. Then, we will click on Credentials, after which we click on “Enable APIs and Services” and enable “Maps JavaScript API” and “Places API” services.

 

Step 4- Register Vue Google Maps Module

Here, in this step, we need to import the “vue2-google-maps” module and inject it into the use() method. This lets us access the map package’s methods and properties in the Vue template.

Then, we have to add the given code in the src/main.js file:

import Vue from 'vue'
import App from './App.vue'
import * as VueGoogleMaps from "vue2-google-maps" // Import package
Vue.config.productionTip = false
Vue.use(VueGoogleMaps, {
  load: {
    key: "GOOGLE MAP API KEY GOES HERE",
    libraries: "places"
  }
});
new Vue({
  render: h => h(App),
}).$mount('#app')

 

Step 5- Create Vue Component

We know that the components are reusable instances. Each component has a unique name which can be invoked by adding it to the main App.vue file.

Further, we have to update the below code in src/components/AddGoogleMap.vue file:

<template>
  <div>
    <div>
      <h2>Vue Js Search and Add Marker</h2>
      <label>
        <gmap-autocomplete @place_changed="initMarker"></gmap-autocomplete>
        <button @click="addLocationMarker">Add</button>
      </label>
      <br/>
 
    </div>
    <br>
    <gmap-map
        :zoom="14"    
        :center="center"
        style="width:100%;  height: 600px;"
      >
      <gmap-marker
        :key="index"
        v-for="(m, index) in locationMarkers"
        :position="m.position"
        @click="center=m.position"
      ></gmap-marker>
    </gmap-map>
  </div>
</template>
 
<script>
export default {
  name: "AddGoogleMap",
  data() {
    return {
      center: { 
        lat: 39.7837304,
        lng: -100.4458825
      },
      locationMarkers: [],
      locPlaces: [],
      existingPlace: null
    };
  },
 
  mounted() {
    this.locateGeoLocation();
  },
 
  methods: {
    initMarker(loc) {
      this.existingPlace = loc;
    },
    addLocationMarker() {
      if (this.existingPlace) {
        const marker = {
          lat: this.existingPlace.geometry.location.lat(),
          lng: this.existingPlace.geometry.location.lng()
        };
        this.locationMarkers.push({ position: marker });
        this.locPlaces.push(this.existingPlace);
        this.center = marker;
        this.existingPlace = null;
      }
    },
    locateGeoLocation: function() {
      navigator.geolocation.getCurrentPosition(res => {
        this.center = {
          lat: res.coords.latitude,
          lng: res.coords.longitude
        };
      });
    }
  }
};
</script>

 

Step 6- Show Google Map

For registering the component in Vue, we will import the component for which we have to define the component in the export object at the same time in the template tag.

We need to add the given code in the src/App.vue file:

<template>
   <div id="app">
      <AddGoogleMap />
   </div>
</template>
 
<script>
import AddGoogleMap from "./components/AddGoogleMap";
 
export default {
  name: 'App',
  components: {
    AddGoogleMap
  }
}
</script>
 
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #000000;
  margin-top: 50px;
}
</style>

 

Step 6- Start Application

So, we have reached the final step of this Vue guide where we have to head over to the command-line tool and type the given command. This will run the Vue app in the browser:

npm run serve

 

Conclusion

In this Vue tutorial, we have learned to integrate Google Maps into Vue 2 apps. We have also seen how to create a Google Map component within the Vue infrastructure.

 

Thanks

 

Leave a Reply

Your email address will not be published. Required fields are marked *