How to create a routes between markers in Angular Maps using the Google Maps Directions API?
The Syncfusion Angular 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.
index.html
<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 Angular Maps component.
app.component.html
<style>
.control-section{
margin-top: 100px;
}
</style>
<div class="control-section">
<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>
<ejs-maps
id="container"
#maps
style="display:block;"
[zoomSettings]="zoomSettings"
[layers]="layers"
>
</ejs-maps>
</div>
</div>
app.component.ts
import { Component, ViewEncapsulation, ViewChild } from '@angular/core';
import {
Maps,
Marker,
Zoom,
MapsModule,
MapsComponent,
NavigationLine,
} from '@syncfusion/ej2-angular-maps';
declare var google: any;
Maps.Inject(Marker, Zoom, NavigationLine);
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
encapsulation: ViewEncapsulation.None,
standalone: true,
imports: [MapsModule],
})
export class AppComponent {
@ViewChild('maps')
public mapObj?: MapsComponent;
constructor() {}
ngOnInit(): void {
this.initMap();
}
private directionsService: any;
private source: string = '';
private destination: string = '';
public initMap() {
this.directionsService = new google.maps.DirectionsService();
const onButtonClick = () => {
this.source = (
document.getElementById('input') as HTMLInputElement
).value.toLowerCase();
this.destination = (
document.getElementById('output') as HTMLInputElement
).value.toLowerCase();
if (
this.source != null &&
this.source != '' &&
this.destination != null &&
this.destination != ''
) {
this.calculateAndDisplayRoute(this.directionsService);
}
};
document.getElementById('route')?.addEventListener('click', onButtonClick);
}
calculateAndDisplayRoute(directionsService: any): void {
this.directionsService.route(
{
origin: { query: this.source },
destination: { query: this.destination },
travelMode: google.maps.TravelMode.DRIVING,
},
(response: any, status: any) => {
if (status === google.maps.DirectionsStatus.OK) {
this.mapObj.zoomSettings.shouldZoomInitially = true;
var markers = this.mapObj.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 =
this.mapObj.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;
} else {
window.alert('Directions request failed due to ' + status);
}
}
);
}
public zoomSettings: object = {
enable: true,
};
public legendSettings: object = { visible: true };
public layers: object[] = [
{
urlTemplate: 'https://tile.openstreetmap.org/level/tileX/tileY.png',
markerSettings: [
{
visible: true,
shape: 'Image',
imageUrl:
'https://ej2.syncfusion.com/angular/demos/assets/maps/images/ballon.png',
width: 20,
height: 20,
},
],
navigationLineSettings: [
{
visible: true,
color: 'black',
angle: 0,
width: 2,
},
],
},
];
}
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 Angular Maps component.
You can refer to our Angular 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 Angular 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!