Change the route style on Google Maps in React
When using Google Maps in React, it is common to need to customize the appearance of the route lines between two points. Fortunately, the Google Maps API provides an easy way to achieve this using the DirectionsRenderer's `polylineOptions` property. By modifying this property, you can change the style of the route line to fit your specific use case.
To change the style of the route line, first, you need to define the `polylineOptions` object with the desired properties, such as stroke color, weight, and opacity. Once you have defined this object, you can pass it as a prop to the `DirectionsRenderer` component in your React code. The API will then use the `polylineOptions` object to render the route line with the custom styles you have specified. This technique allows you to create visually appealing and informative route lines that match your project's design and style guidelines.
Demo Application
Output - Change the route style on Google Maps in React - Clue Mediator
Change the route style on google maps in React
1. Project structure
-
route-style-google-maps-react
-
node_modules
-
public
- index.html
-
src
- App.js
- GMap.js
- index.css
- index.js
-
package-lock.json
-
package.json
-
README.md
-
2. Package dependencies
Run the following command to install @googlemaps/js-api-loader npm package.
npm i @googlemaps/js-api-loader
You will find the version of the following packages in React application.
react
^18.2.0
@googlemaps/js-api-loader
^1.15.1
3. Implementation
We need to use the `polylineOptions` property of the `DirectionsRenderer` to modify the style of the route.
new window.google.maps.DirectionsRenderer({
polylineOptions: new window.google.maps.Polyline({
strokeOpacity: 0,
icons: [{
icon: {
path: "M 0,-0.1 0,0.1",
strokeOpacity: 0.8,
strokeColor: 'red',
scale: 5,
},
offset: "0",
repeat: "10px",
}],
})
});
Refer to the following files for the implementation.
GMap.js
import React, { useEffect, useRef, useState } from 'react';
const GMap = () => {
const googleMapRef = useRef(null);
const [map, setMap] = useState(null);
useEffect(() => {
const googleMap = initGoogleMap();
setMap(googleMap);
}, []);
useEffect(() => {
if (!map) return;
const routeOptions = new window.google.maps.Polyline({
strokeOpacity: 0,
icons: [{
icon: {
path: "M 0,-0.1 0,0.1",
strokeOpacity: 0.8,
strokeColor: 'red',
scale: 5,
},
offset: "0",
repeat: "10px",
}],
});
var directionsService = new window.google.maps.DirectionsService();
var directionsRenderer = new window.google.maps.DirectionsRenderer({ polylineOptions: routeOptions });
var haight = new window.google.maps.LatLng(37.7699298, -122.4469157);
var oceanBeach = new window.google.maps.LatLng(37.7683909618184, -122.51089453697205);
var request = {
origin: haight,
destination: oceanBeach,
travelMode: 'WALKING'
};
directionsService.route(request, function (response, status) {
if (status == 'OK') {
directionsRenderer.setDirections(response);
directionsRenderer.setMap(map);
}
});
}, [map])
const initGoogleMap = () => {
return new window.google.maps.Map(googleMapRef.current, {
center: new window.google.maps.LatLng(37.7699298, -122.4469157),
zoom: 8
});
}
return <div 300="" ref={googleMapRef} style={{ width: 600, height: }}>
}
export default GMap;</div>
App.js
import React, { useState, useEffect } from 'react';
import { Loader } from '@googlemaps/js-api-loader';
import GMap from './GMap';
// API key of the google map
const GOOGLE_MAP_API_KEY = '<your_google_map_api_key>';
const App = () => {
const [loadMap, setLoadMap] = useState(false);
useEffect(() => {
const options = {
apiKey: GOOGLE_MAP_API_KEY,
version: "weekly",
libraries: ['geometry']
};
new Loader(options).load().then(() => {
setLoadMap(true);
}).catch(e => {
console.error('Sorry, something went wrong: Please try again later. Error:', e);
});
}, []);
return (
<div class="App">
<h4>Change the route style on google maps in React - <a href="https://www.cluemediator.com">Clue Mediator</a></h4>
{!loadMap ? <div>Loading...</div> : <gmap>}
<br>
<small><b>Note:</b> In order to make it work, you have to set the YOUR_GOOGLE_MAP_API_KEY in App.js file. </small>
</gmap></div>
);
}
export default App;
</your_google_map_api_key>
4. Output
Run your application and check the output in the browser.
Live Demo
That's it for today.
Thank you for reading. Happy Coding..!!