How to create a routes between markers in React Maps using the Google Maps Directions API?
The Syncfusion React Maps component is designed to display maps and visualize the provided data. You can also display routes between the source and destination markers using the navigation line feature. To create a route, you will need the source and destination locations, as well as any locations in between. The coordinates for these locations can be fetched from external sources, such as the Google Directions API. In this section, we will demonstrate how to obtain these coordinate points and integrate them into the Maps to plot a route between the designated locations.
In the following example, we created two text boxes to capture the source and destination locations, along with a button to add routes between these specified locations. First, we initialized the Google Maps Directions Service in the initMap method, generating coordinates for the locations and routes based on user-defined input values. The coordinate points retrieved from the Google Maps Directions API are added as markers using the dataSource property of the markerSettings in the Maps component. Additionally, the fetched coordinates for the route between the source and destination are updated in the latitude and longitude properties of the navigationLineSettings. This allows us to visualize markers and navigation lines on the map, providing users with an interactive experience to obtain directions and view the path between the specified locations.
To access the Google Maps Directions API, you need to include the following script, as shown below.
<script src="https://maps.googleapis.com/maps/api/js?key=Your_Key&callback=initMap&v=weekly" defer></script>
The code example below demonstrates how to create a route between markers on the Maps by fetching coordinates from the Google Maps Directions API in the React Maps component.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Syncfusion React Chart-Add DataSource</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Essential JS 2 for React Components" />
<meta name="author" content="Syncfusion" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=Your_Key&callback=initMap&v=weekly"
defer
></script>
<script src="systemjs.config.js"></script>
<style>
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#container {
height: 500px;
display: block;
}
</style>
</head>
<body style="margin-top: 100px">
<label for="textInput"><b>Source</b> : </label>
<input type="text" id="input" name="textInput" /><br />
<br />
<label for="textOutput"><b>Destination</b> : </label>
<input type="text" id="output" name="textOutput" /><br /><br />
<button id="route">Add Route</button>
<div id="container">
<div id="loader">Loading....</div>
</div>
</body>
</html>
index.js
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import {
MapsComponent,
LayersDirective,
LayerDirective,
MarkersDirective,
MarkerDirective,
NavigationLinesDirective,
NavigationLineDirective,
Marker,
NavigationLine,
Zoom,
Inject,
} from '@syncfusion/ej2-react-maps';
export function App() {
var source;
var destination;
var mapsInstance;
useEffect(() => {
initMap();
}, []);
function initMap() {
const directionsService = new google.maps.DirectionsService();
const onButtonClick = function (event) {
source = document.getElementById('input').value.toLowerCase();
destination = document.getElementById('output').value.toLowerCase();
if (
source != '' &&
source != null &&
destination != '' &&
destination != null
) {
calculateAndDisplayRoute(directionsService);
}
};
document.getElementById('route').addEventListener('click', onButtonClick);
}
function calculateAndDisplayRoute(directionsService) {
directionsService
.route({
origin: {
query: source,
},
destination: {
query: destination,
},
travelMode: google.maps.TravelMode.DRIVING,
})
.then((response) => {
mapsInstance.zoomSettings.shouldZoomInitially = true;
var markers = mapsInstance.layersCollection[0].markerSettings;
markers[0].dataSource = [];
markers[0].dataSource.push({
latitude: response.routes[0].legs[0].start_location.lat(),
longitude: response.routes[0].legs[0].start_location.lng(),
});
markers[0].dataSource.push({
latitude: response.routes[0].legs[0].end_location.lat(),
longitude: response.routes[0].legs[0].end_location.lng(),
});
var navigationlines =
mapsInstance.layersCollection[0].navigationLineSettings;
var latLngs = response.routes[0].overview_path;
var latitudes = [];
var longitudes = [];
for (var i = 0; i < latLngs.length; i++) {
latitudes.push(latLngs[i].lat());
longitudes.push(latLngs[i].lng());
}
navigationlines[0].latitude = latitudes;
navigationlines[0].longitude = longitudes;
})
.catch((e) => window.alert('Directions request failed due to ' + status));
}
return (
<MapsComponent
zoomSettings={{
enable: true,
}}
ref={(g) => (mapsInstance = g)}
>
<Inject services={[Marker, NavigationLine, Zoom]} />
<LayersDirective>
<LayerDirective urlTemplate="https://tile.openstreetmap.org/level/tileX/tileY.png">
<MarkersDirective>
<MarkerDirective
visible={true}
height={20}
width={20}
shape="Image"
imageUrl="https://ej2.syncfusion.com/react/demos/src/maps/images/ballon.png"
></MarkerDirective>
</MarkersDirective>
<NavigationLinesDirective>
<NavigationLineDirective
visible={true}
color="black"
angle={0}
width={2}
/>
</NavigationLinesDirective>
</LayerDirective>
</LayersDirective>
</MapsComponent>
);
}
const root = createRoot(document.getElementById('container'));
root.render(<App />);
The following screenshot illustrates the output of the above code snippet.
NOTE : To run the sample above, you need to add your API key to access the Google Maps Directions API.
Conclusion
I hope you enjoyed learning how to obtain the coordinate points from the external source and integrate them into the React Maps component.
You can refer to our React Maps feature tour to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Maps example to understand how to create and visualize the data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!