Integrating Google Maps into Vue Applications
Published: 2023-10-21 00:50:27

_This article was originally published on [OpenReplay blog](https://blog.openreplay.com/integrating-google-maps-into-vue-applications/)._

[Google Maps](https://www.google.com/maps) is a powerful tool for displaying interactive maps and location-based services on the web. Imagine you're creating a travel app that helps users plan trips. With Google Maps, you can display different routes, points of interest, and allow users to zoom and click on markers for a better experience.
Integrating Google Maps features into a Vue.js application can enhance the user experience and provide valuable geospatial features. In this tutorial, we will explore the process of integrating Google Maps into a Vue application using the popular [Vue-google-maps](https://vue-map.netlify.app/) library.
## Prerequisites
Before we fully dive into the tutorial, we should have the following requirements to follow along and complete the tutorial.
- [Node.js](https://nodejs.org/en) and [npm](https://www.npmjs.com/) installed on your system.
- You will need a [Google Maps account](https://console.cloud.google.com/).
- You should be familiar with Vue.
## Getting Google Map API Key
I assume you already have a Google Maps account. If you don't have one yet, you can create a new account by following these steps. 
- Login to the [Google Cloud Console.](https://console.cloud.google.com/)
- Click on the `Select a Project` drop-down menu and choose `New Project.` Name your project and click `Create.`
- Navigate to `APIs & Services` → `Dashboard` from the Cloud Console's navigation menu.
- Click the `+ ENABLE APIS AND SERVICES` button.
- Search for `Maps JavaScript API` and select it.
- Click on the `Enable` button to activate the API for your project.
- Go back to the navigation menu and choose `APIs & Services` → `Credentials.`
- Click `Create Credentials` and select `API key.`
- Copy the generated API key and ensure its security. You'll need to add this key to your Vue.js application to access Google Maps services.
## Vue-google-maps Installation
[Vue-google-maps](https://vue-map.netlify.app/) is a popular integration for Vue.js applications that enables seamless incorporation of Google Maps functionality. It offers a collection of Vue components that simplify the process of implementing interactive maps, markers, and geolocation-based features within Vue applications.
Before installing `vue-google-maps`, let's create a new Vue project. To do so, open your terminal and execute the following command:
```bash
npm create vue@latest
```
Follow the instructions provided by the prompt to create a new Vue project, as shown in the image below.
![](https://lh5.googleusercontent.com/neQOKvEzyHpyHDUI3kyFA1zNzZ3JBAJdkUZy3LqW8H8B2DVE2Oegf8vcBma_4OPoeZMrBII3UDx_MDYNBpd0Gla2T6OQJ84L7VTyQSXmwHflq0Z1t02WdkaSK9o2VsV_pqpebTszAfj_nd_vO2tLgQA)
Next, we will install the `vue-google-maps` package into the application by running the following command:
```bash
npm install -S @fawmi/vue-google-maps
```
## Vue-google-maps Configuration
After installing the library, you need to configure it to use your Google Maps API key. In your Vue project, open the main.js file and add the following code:
```js
import { createApp } from "vue";
import VueGoogleMaps from "@fawmi/vue-google-maps";
import App from "./App.vue";
import "./assets/main.css";
const app = createApp(App);
app.use(VueGoogleMaps, {
    load: {
        key: 'YOUR_GOOGLE_MAPS_API_KEY,
    },
  })
  .mount("#app");
```
Replace `YOUR_GOOGLE_MAPS_API_KEY` with the API key you obtained earlier and save the code.
At this stage, if you reload the application, an import issue will occur. To resolve this error, add the following configuration to your `vite.config.js` file.
```js
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  optimizeDeps: {
    include: ["@fawmi/vue-google-maps", "fast-deep-equal"],
  },
});
```
## Displaying a map View
Now that the library is set up, let's create a component to display the Google Map. In your Vue project, open the `App.vue` file. In the `App.vue` file, we use the `GMapMap` component to display a map in our application. To achieve this, replace the existing App.vue code with the following code. 
```htmlmixed
<template>
  <GMapMap
    :center="center"
    :zoom="7"
    map-type-id="terrain"
    style="width: 1000px; height: 800px"
  >
  </GMapMap>
</template>
<script>
  export default {
    name: "App",
    data() {
      return {
        center: { lat: 51.093048, lng: 6.84212 },
      };
    },
  };
</script>
```
From the above code we have:
- The `GMapMap` component is used to display the Google Map within the template section.
- The `:center` prop is used to set the `center` position of the map. In this case, it's set to latitude `51.093048` and longitude `6.842120`.
- The `:zoom` prop sets the initial zoom level of the map to 7.
- The `map-type-id` prop defines the type of map to display. Here, `terrain` type is used.

Now, start the application using `npm run dev`. You should see the map displayed in the application, as shown in the image below.

![](https://lh4.googleusercontent.com/_13lyNSQnZs5T1HcofTDy1kdin-LwIkidtDGsMFd8fIXuPY4SZ9dPcpl8vc-hfOWBsHGiE6h2RhDxTFo-hulBnp-h-vz_uQk6BOAvYsczGxHdnq5FJ-RihywoxzoKHgxMl-jgEJaLs7DQ9r6h2M729s)
## Getting current user location - Map Marker
We can also obtain the current location of a user using the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API), which will prompt the user to allow the application to access their location. Then, we can add a marker to the user's location on the map to indicate their position. To achieve this, replace the code in `app.vue` with the following code.
```htmlmixed
<template>
  <GMapMap
    :center="center"
    :zoom="zoom"
    map-type-id="terrain"
    style="width: 1000px; height: 800px"
  >
    <GMapMarker
      :key="marker.id"
      v-for="marker in markers"
      :position="marker.position"
    />
  </GMapMap>
</template>
<script>
  export default {
    name: "App",
    data() {
      return {
        center: { lat: 6.465422, lng: 3.406448 },
        zoom: 7,
        markers: [
          {
            id: "user-marker",
            position: {
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            },
          },
        ],
      };
    },
    methods: {
      geolocate: function () {
        navigator.geolocation.getCurrentPosition((position) => {
          this.center = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          this.markers.push({
            id: "user-marker",
            position: {
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            },
          });
        });
      },
    },
    mounted() {
      this.geolocate();
    },
  };
</script>
```
In the code above, we wrap the `GMapMarker` within the `GMapMap` component, which contains all the props used for the marker indicator. Then, we utilize `getCurrentPosition` from the Geolocation API to retrieve the user's location coordinates and update them within the GMapMarker component. 

Refresh the application; this will add a map marker to the user's current location, as shown in the image below:
![](https://lh4.googleusercontent.com/x6xLrx0yFoCp2_tWAlsNK7LBnWdQfVq63VFYmSpW1WXKThhvZjpX7dq82eaSkvu_DfYTT3mJNtA2ExKKLpqfujN7rVxQ8kMC1q13Ea3paKABewxg8EKKcrimGuM2__mXgH6QyR9rEusrAXpYpnSSSNs)
## Using Location Search
Now, let's implement a location search feature that will allow users to search for places and display them on the map. Before we can add location search features into our vue application, we need to first place libraries to vite.config.js. Using the code below:
```json
//...
load: {
  key: 'YOUR_GOOGLE_MAPS_API_KEY',
  libraries: "places"
},
//...
```
Next, we will use the GMapAutocomplete component to add location searches to the vue application. To achieve this update app.vue code with the following code.
```htmlmixed
<template>
  <div>
    <GMapAutocomplete
      placeholder="This is a placeholder"
      @place_changed="setPlace"
      style="font-size: large"
    ></GMapAutocomplete>
    <GMapMap
      :center="mapCenter"
      :zoom="mapZoom"
      style="width: 1000px; height: 700px"
    >
      <GMapMarker :position="markerPosition" />
    </GMapMap>
  </div>
</template>
<script>
  export default {
    name: "App",
    data() {
      return {
        mapCenter: { lat: 6.465422, lng: 3.406448 }, // Initial center
        mapZoom: 7, // Initial zoom level
        markerPosition: null, // Marker position will be set based on searched location
      };
    },
    methods: {
      setPlace(place) {
        this.markerPosition = {
          lat: place.geometry.location.lat(),
          lng: place.geometry.location.lng(),
        };
        this.mapCenter = {
          lat: place.geometry.location.lat(),
          lng: place.geometry.location.lng(),
        };
      },
    },
  };
</script>
```
In the code above, we added an input field where users can easily search for places and then display the location on the map by indicating the selected place with a map marker. The code will produce the result below, as shown in the image.
![](https://lh6.googleusercontent.com/4EUcRas2US-CIMylYE3-qY50jlevOgDiSDmnJzHdaSWIGjShjxyNhscKC8nPonAV0g_NCemJVFL5v8Nh3lOW3jNL4B_urab09P2rJX2g5Oxf9ISqng0zq8NBzngeNvVijak7Kw4cs2ezVrarOtVgwL8)
## Conclusion
Now you have successfully integrated Google Maps into your Vue.js application using the [Vue-google-maps](https://vue-map.netlify.app/) library. You now have a map view with location markers and the ability to search for locations. Feel free to further enhance your application with additional features such as custom markers, directions, or geolocation-based services.

Remember to adhere to Google Maps API usage policies and consider implementing additional security measures when utilizing location-based services in your application. Happy mapping!

https://blog.openreplay.com/integrating-google-maps-into-vue-applications/