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:
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:
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.
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:
To begin, let’s create a new Vue project from scratch. Open your terminal and run the following command:
npm create vue@latest
Once your project is created, proceed to install the vue-google-maps library:
npm install -S @fawmi/vue-google-maps
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');
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", ], },
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 }" />
Here’s how the map will be rendered on the page:
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 loadedzoom
: specifies the initial zoom level of the mapmap-type-id
: configures the map type to “terrain,” displaying topographic features such as mountains and valleysstyle
: defines the width and height of the map container, allowing you to adjust the map’s dimensions to suit your layoutoptions
: 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"
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 mapGMapCluster
: Allows you to cluster Marker
componentsGMapInfoWindow
: Allows you to add an info window to your componentsGMapPolyline
: Allows you to add a polyline to the map that shows a path between two or more pointsGMapAutocomplete
: Provides autocomplete suggestions for Google PlacesThere are also components like GMapRectangle
, GMapCircle
, and GMapPolygon
for adding various shapes to your map to help indicate a general area.
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>
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
componentopened
: 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 clickedoptions
: 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 componentclickable
: 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 }) } }
By calling getUserLocation()
, you can trigger the process to fetch the user’s location and update the marker’s position accordingly.
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" },
Then we can access the component in the Vue project:
<GMapAutocomplete placeholder="Search for a location" @place_changed="setPlace" style="font-size: medium" > </GMapAutocomplete>
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 }
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:
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!
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 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.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
One Reply to "How to integrate Google Maps into a Vue 3 application"
you shouldn’t have to rely on a vue plug-in to be able to implement google maps into a vue application.