DEV Community

Cover image for How to integrate Google Maps into a Vue 3 application
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

How to integrate Google Maps into a Vue 3 application

Written by Abiola Farounbi✏️

Location-based services have revolutionized the way users interact with web applications. Whether you're building a cutting-edge delivery tracking application, a neighborhood restaurant finder, or you just want to enhance your website with dynamic maps, integrating Google Maps into your project can provide a boost to UX.

In this hands-on guide, we will explore the step-by-step process of integrating Google Maps into a Vue 3 application, from the basics to advanced features that will genuinely enhance the UX of your app.

Jump ahead:

Google Maps Platform: An overview

The Google Maps Platform provides a diverse array of APIs, each designed to cater to different aspects of mapping and location-based services. These APIs are the gateway to harnessing the different use cases for Google Maps within your applications and websites.

Here are some key APIs within the Google Maps Platform:

  • Maps JavaScript API: Allows developers to embed Google Maps into their webpages, with options to customize the map appearance; add markers, layers, overlays, and events; and access various map features and controls
  • Maps Static API: Allows developers to request static map images that can be embedded into webpages or applications, with options to customize the map size, zoom level, format, language, region, and style
  • Maps Embed API: Allows developers to embed an interactive Google Map into their webpages or applications, with options to choose from different map modes, including directions, search, view, and street view
  • Directions API: Allows developers to request direction data for various modes of transportation, such as driving, walking, cycling, and transit. The service also provides information on distance, duration, traffic conditions, waypoints, and alternative routes
  • Distance Matrix API: Allows developers to request travel distance and time data for a set of origins and destinations. The service also provides information on traffic conditions and modes of transportation
  • Geocoding API: Allows developers to convert addresses to geographic coordinates (geocoding) or vice versa (reverse geocoding). The service also provides information on address components, types, and formats
  • Geolocation API: Allows developers to determine the geographic location of a device or user based on various sources of information, such as IP addresses, cell towers, Wi-Fi access points, GPS signals, or sensor data
  • Places API: Allows developers to access information on millions of places around the world, such as names, addresses, phone numbers, ratings, reviews, photos, and operating hours. The service also provides features such as autocomplete, search nearby, text search, and place details
  • Roads API: Allows developers to access road and speed limit data for a given location or route. The service also provides features such as snap to roads, nearest roads, and speed limits
  • Time Zone API: Allows developers to request time zone data for a given location or timestamp. The service also provides information on daylight saving time and time offset from UTC

Although not every aspect of the Google Maps API suite may be necessary for your specific project, you gain the freedom to select the APIs that align most effectively with your requirements. By understanding the capabilities of each API, you can select those that best suit your project's requirements, ensuring a seamless integration of Google Maps functionality into your application.

To get access to the Google Maps Platform, you‘ll need a Google Maps API key. The API key is a unique code that verifies requests linked to your project, serving both usage and billing verification functions. You must have at least one API key associated with your project to use Google Maps Platform products.

To create an API key, you need a project with a billing account and the Maps JavaScript API enabled. You can follow the steps in the documentation to create and restrict your API key.

Integrating Google Maps in a Vue 3 app

For this demo, we’ll use the vue-google-maps package to integrate Google Maps into our Vue 3 application. vue-google-maps simplifies the process of incorporating Google Maps into Vue apps by offering components and directives that wrap the Google Maps JavaScript API, providing a declarative approach to accessing its features. With this library, you can effortlessly display maps, markers, info windows, polygons, and more.

Before diving into the integration process, let's ensure you have the necessary prerequisites in place:

  • A code editor of your choice
  • Node.js and npm installed on your machine
  • A basic understanding of Vue.js
  • A Google Maps Platform account with a valid API key

To begin, let's create a new Vue project from scratch. Open your terminal and run the following command:

npm create vue@latest
Enter fullscreen mode Exit fullscreen mode

Once your project is created, proceed to install the vue-google-maps library:

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

With the library installed, it’s time to integrate it into your Vue project. Add the following code to your main.js file:

import VueGoogleMaps from '@fawmi/vue-google-maps';
const app = createApp(App);
app.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_API_KEY',
  },
}).mount('#app');
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_API_KEY' with the unique API key you generated earlier.

At this stage, when you refresh your application, you may encounter an import issue. To resolve this error, include the following configuration in your vite.config.js file:

optimizeDeps: {
  include: [
    "@fawmi/vue-google-maps",
    "fast-deep-equal",
  ],
},
Enter fullscreen mode Exit fullscreen mode

Rendering a simple map with vue-google-maps

The vue-google-maps library provides prebuilt components that allow you to use Google Maps features directly in a Vue project. Let’s take a look at how to render a simple map on your page with the base map component, GMapMap:

    <GMapMap
      :center="{ lat: 51.5072, lng: 0.1276 }"
      :zoom="10" 
      map-type-id="terrain" 
      style="width: 100vw; height: 20rem"
      :options="{
        zoomControl: true,
        mapTypeControl: true,
        scaleControl: true,
        streetViewControl: true,
        rotateControl: true,
        fullscreenControl: true
      }"
    />
Enter fullscreen mode Exit fullscreen mode

Here’s how the map will be rendered on the page: Simple Google Map Rendered in Our Vue 3 App This GMapMap component comes with a number of props that allow us to customize how the map will be rendered:

  • center: sets the initial center coordinates of the map using latitude and longitude values, determining where the map focuses when first loaded
  • zoom: specifies the initial zoom level of the map
  • map-type-id: configures the map type to "terrain," displaying topographic features such as mountains and valleys
  • style: defines the width and height of the map container, allowing you to adjust the map's dimensions to suit your layout
  • options: provides an object containing various map options, allowing you to customize specific UI components of the map. You can also disable all options at once by setting the disableDefaultUI prop to "true"

Implementing advanced Google Maps features

In this section, we'll look at some advanced features you can add to the map to make it more interactive and useful. vue-google-maps has a number of prebuilt components you can use to layer additional functionality on top of the base GMapMap component:

  • GMapMarker: Allows you to indicate specific locations on the map
  • GMapCluster: Allows you to cluster Marker components
  • GMapInfoWindow: Allows you to add an info window to your components
  • GMapPolyline: Allows you to add a polyline to the map that shows a path between two or more points
  • GMapAutocomplete: Provides autocomplete suggestions for Google Places

There are also components like GMapRectangle, GMapCircle, and GMapPolygon for adding various shapes to your map to help indicate a general area.

Adding markers with info windows

Adding markers on your map is a fundamental feature that can help users identify specific locations or points of interest. Moreover, you can enhance the user experience by attaching info windows to these markers, allowing users to access additional information with a simple click.

We'll use the GMapMarker component along with GMapInfoWindow to achieve this functionality:

      <!-- Marker to display the searched location -->
      <GMapMarker
        :key="markerDetails.id"
        :position="markerDetails.position"
        :clickable="true"
        :draggable="false"
        @click="openMarker(markerDetails.id)"
      >
        <!-- InfoWindow to display the searched location details -->
          <GMapInfoWindow
            v-if="locationDetails.address != ''"
            :closeclick="true"
            @closeclick="openMarker(null)"
            :opened="openedMarkerID === markerDetails.id"
            :options="{
              pixelOffset: {
                width: 10,
                height: 0
              },
              maxWidth: 320,
              maxHeight: 320
            }"

          >
            <div class="location-details">
                <p> Added Info </p>
            </div>
          </GMapInfoWindow>
      </GMapMarker>
Enter fullscreen mode Exit fullscreen mode

GMapMarker and GMapInfoWindow offer a range of optional props that you can use to tailor the appearance and behavior of markers and info windows according to your specific requirements. This flexibility allows you to create a truly customized and interactive mapping experience for your users.

Some of the more useful props include:

  • position: This prop specifies the coordinates of the marker on the map. It can be either an object with lat and lng properties, or a function that returns such an object. The position prop is required for the GMapMarker component
  • opened: This prop controls whether the info window is open or closed. It can be either a Boolean value or a function that returns a Boolean value. The opened prop is required for the GMapInfoWindow component. If set to true, the info window will be displayed when the map is loaded. If set to false, the info window will be hidden until the marker is clicked
  • options: This prop allows you to customize the appearance and behavior of the marker and the info window. The options prop is optional for both components and accepts different properties depending on the component
  • **clickable**: This prop determines whether users can click the marker. The clickable prop is optional for both components and defaults to true
  • draggable: This prop determines whether the marker can be dragged or not. It can be either a boolean value or a function that returns a boolean value. The draggable prop is optional for both components.

To enhance your map further, you can implement a feature that retrieves the user's location and displays it on the map using a marker. This can be achieved with the JavaScript Geolocation API:

// Setting the default coordinates to London
    const coords = ref({ lat: 51.5072, lng: 0.1276 })
    // Marker Details
    const markerDetails = ref({
      id: 1,
      position: coords.value
    })
    // Get users' current location
    const getUserLocation = () => {
    // Check if geolocation is supported by the browser
      const isSupported = 'navigator' in window && 'geolocation' in navigator
      if (isSupported) {
        // Retrieve the user's current position
        navigator.geolocation.getCurrentPosition((position) => {
          coords.value.lat = position.coords.latitude
          coords.value.lng = position.coords.longitude
        })
      }
    }
Enter fullscreen mode Exit fullscreen mode

By calling getUserLocation(), you can trigger the process to fetch the user's location and update the marker's position accordingly.

Implementing autocomplete for location search

The library also provides access to Google Places, which allows you to use the autocomplete search feature to easily find different places on the map. First, we have to load the library from the main.js file:

  load: {
    key: GOOGLE_MAPS_API_KEY,
    libraries: "places"
  },
Enter fullscreen mode Exit fullscreen mode

Then we can access the component in the Vue project:

      <GMapAutocomplete
        placeholder="Search for a location"
        @place_changed="setPlace"
        style="font-size: medium"
      >
      </GMapAutocomplete>
Enter fullscreen mode Exit fullscreen mode

This code snippet creates a search input box with an autocomplete feature that allows users to easily find different places on the map. Additionally, with the data obtained from the place, we can then update the marker position and the info window details:

    // Set the location based on the place selected
    const setPlace = (place) => {
      coords.value.lat = place.geometry.location.lat()
      coords.value.lng = place.geometry.location.lng()
      // Update the location details
      locationDetails.value.address = place.formatted_address
      locationDetails.value.url = place.url
    }
Enter fullscreen mode Exit fullscreen mode

When a user selects a place from the autocomplete suggestions, the setPlace function is triggered. It extracts the latitude and longitude of the selected place and updates the marker's position on the map. Additionally, it updates the location details, such as the address and URL, to provide users with relevant information:

Demo Showing the Advanced Google Maps Features We Implemented in Our Vue 3 App

Conclusion

In conclusion, this article has equipped you with the knowledge to seamlessly integrate Google Maps into your Vue 3 application. From understanding the diverse features of the Google Maps Platform to implementing advanced map features using the vue-google-maps library.

With this knowledge, you can enhance your application by providing users with dynamic and interactive location-based services. You check out the full application here on GitHub.

If you have any questions, feel free to reach out to me on Twitter or leave a comment below. Happy coding!


Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.

LogRocket Signup

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - Start monitoring for free.

Top comments (0)