DEV Community

Cover image for Integrating Google Maps into Vue Applications
popoola Temitope
popoola Temitope

Posted on

Integrating Google Maps into Vue Applications

This article was originally published on OpenReplay blog.

Google 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 library.

Prerequisites

Before we fully dive into the tutorial, we should have the following requirements to follow along and complete the tutorial.

  • Node.js and npm installed on your system.
  • You will need a Google Maps account.
  • 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.
  • Click on the Select a Project drop-down menu and choose New Project. Name your project and click Create.
  • Navigate to APIs & ServicesDashboard 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 & ServicesCredentials.
  • 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 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:
npm create vue@latest
Enter fullscreen mode Exit fullscreen mode

Follow the instructions provided by the prompt to create a new Vue project, as shown in the image below.

Next, we will install the vue-google-maps package into the application by running the following command:

npm install -S @fawmi/vue-google-maps
Enter fullscreen mode Exit fullscreen mode

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:

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");
Enter fullscreen mode Exit fullscreen mode

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.

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"],
  },
});
Enter fullscreen mode Exit fullscreen mode

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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.

Getting current user location - Map Marker

We can also obtain the current location of a user using the 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.

<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>
Enter fullscreen mode Exit fullscreen mode

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:

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:

//...
load: {
  key: 'YOUR_GOOGLE_MAPS_API_KEY',
  libraries: "places"
},
//...
Enter fullscreen mode Exit fullscreen mode

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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.

Conclusion

Now you have successfully integrated Google Maps into your Vue.js application using the Vue-google-maps 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/

Top comments (0)