How to create routes between markers in Blazor Maps using the Google Maps Directions API?
The Syncfusion Blazor 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 this example, we have created two text boxes to capture the source and destination locations, along with a button to add routes between the specified locations. Since we are using the Google Maps JavaScript Directions API, we need to define a JavaScript interop method called initMap to generate routes based on user-defined values. The coordinate points for the source and destination are retrieved from the Google Maps Directions API and added as markers using the DataSource property of the MapsMarker tag in the Maps component. Additionally, we fetch the coordinates for the route between the source and destination, which are then updated in the Latitude and Longitude properties of the MapsNavigationLine tag in the Maps component. 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 and the initMap JavaScript method, you need to include the following script, as shown below.
_Host.cshtml
<script src="https://maps.googleapis.com/maps/api/js?key=Your_Key&callback=initMap&v=weekly" defer></script>
<script src="~/external-source.js"></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 Blazor Maps component.
Index.razor
@using Syncfusion.Blazor.Maps
@using System.Collections.ObjectModel;
@inject IJSRuntime JSRuntime
@using System.Text.Json;
<div>
<label for="source"><b>Source</b> :</label>
<input type="text" id="source" @bind="markerSource" />
</div>
<br />
<div>
<label for="destination"><b>Destination</b> :</label>
<input type="text" id="destination" @bind="markerDestination" />
</div>
<br />
<button @onclick="AddRoutes">Add Routes</button>
<div>
<SfMaps ID="Maps">
<MapsZoomSettings Enable="true" MaxZoom="19" ShouldZoomInitially="true" EnablePanning="true">
</MapsZoomSettings>
<MapsLayers>
<MapsLayer UrlTemplate="https://tile.openstreetmap.org/level/tileX/tileY.png" TValue="string">
@if (Cities != null)
{
<MapsMarkerSettings>
<MapsMarker Visible="true" Height="20" Width="20" DataSource="Cities" TValue="MapMarker" Shape="MarkerType.Image" ImageUrl="https://blazor.syncfusion.com/demos/_content/blazor_server_common_net8/images/maps/ballon.png">
</MapsMarker>
</MapsMarkerSettings>
}
<MapsNavigationLines>
@if (LatitudePoints.Count > 1 && LongitudePoints.Count > 1)
{
<MapsNavigationLine Visible="true" Angle="0" Color="black" Width="2" Latitude="@LatitudePoints.ToArray()" Longitude="@LongitudePoints.ToArray()"></MapsNavigationLine>
}
</MapsNavigationLines>
</MapsLayer>
</MapsLayers>
</SfMaps>
</div>
<br />
@code
{
private string markerSource = string.Empty;
private string markerDestination = string.Empty;
public List<double> LatitudePoints = new List<double>();
public List<double> LongitudePoints = new List<double>();
private ObservableCollection<MapMarker> Cities = new ObservableCollection<MapMarker>();
public class MapMarker
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Name { get; set; }
}
public void ClearPoints()
{
Cities.Clear();
LatitudePoints.Clear();
LongitudePoints.Clear();
}
public async Task AddRoutes()
{
ClearPoints();
if (markerSource != string.Empty && markerDestination != string.Empty)
{
var response = await JSRuntime.InvokeAsync<JsonElement>("initMap", markerSource, markerDestination);
Cities.Add(new MapMarker
{
Latitude = response.GetProperty("startLocation").GetProperty("latitude").GetDouble(),
Longitude = response.GetProperty("startLocation").GetProperty("longitude").GetDouble()
});
Cities.Add(new MapMarker
{
Latitude = response.GetProperty("endLocation").GetProperty("latitude").GetDouble(),
Longitude = response.GetProperty("endLocation").GetProperty("longitude").GetDouble()
});
foreach (var point in response.GetProperty("path").EnumerateArray())
{
LatitudePoints.Add(point.GetProperty("latitude").GetDouble());
LongitudePoints.Add(point.GetProperty("longitude").GetDouble());
}
}
}
}
external-source.js
var initMap = function (source, destination) {
return new Promise((resolve, reject) => {
const directionsService = new google.maps.DirectionsService();
directionsService
.route({
origin: {
query: source,
},
destination: {
query: destination,
},
travelMode: google.maps.TravelMode.DRIVING,
})
.then((response) => {
if (response && response.routes && response.routes[0] && response.routes[0].legs[0]) {
const coordinates = response.routes[0].legs[0];
const startLocation = {
latitude: coordinates.start_location.lat(),
longitude: coordinates.start_location.lng()
};
const endLocation = {
latitude: coordinates.end_location.lat(),
longitude: coordinates.end_location.lng()
};
const path = coordinates.steps.map(step => ({
latitude: step.start_location.lat(),
longitude: step.start_location.lng()
}));
resolve({
startLocation: startLocation,
endLocation: endLocation,
path: path
});
} else {
reject("No routes found.");
}
})
.catch((e) => window.alert("Directions request failed due to " + e));
});
};
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 Blazor Maps component.
You can refer to our Blazor 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 Blazor 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!