I'm currently implementing a logistics app and I integrated Google Maps there. Now I need to show the Google Map Navigation within the app.
I have added a new page called Navigation.razor and using it as a child component within the main component.
At the moment, the map is only showing the path between the given two positions. How can I modify it to show the navigation?
<div class="card my-card">
<div id="map2" style="width: 100%; height: 200px"></div>
</div>
<script>
window.initNavigation = function (origin, destination) {
map = new google.maps.Map(document.getElementById("map2"), {
zoom: 11,
center: { lat: origin.Latitude, lng: origin.Longtitude },
disableDefaultUI: true,
zoomControl: false,
mapTypeControl: false,
streetViewControl: false
});
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: false, // Set to true if you want to customize markers
panel: document.getElementById("directions-panel")
});
const request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
showNavigationSteps(result);
} else {
console.error("Directions request failed due to " + status);
}
});
}
function showNavigationSteps(directionResult) {
const steps = directionResult.routes[0].legs[0].steps;
const directionsPanel = document.getElementById("directions-panel");
directionsPanel.innerHTML = ""; // Clear any previous steps
steps.forEach((step, index) => {
const instructionElement = document.createElement("p");
instructionElement.innerHTML = `${index + 1}. ${step.instructions}`;
directionsPanel.appendChild(instructionElement);
});
}
</script>
@code {
@inject NavigationManager navigation
@inject LocationService locationService
@inject IJSRuntime JS
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
try
{
await RequestLocationPermissionAndInitializeMap();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private async Task RequestLocationPermissionAndInitializeMap()
{
var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
if (status == PermissionStatus.Granted)
{
var (location, locationFetchingError) = await locationService.GetCurrentLocationAsync();
string origin = $"{location.Latitude},{location.Longitude}";
// Pass the destination address to JavaScript if permission is granted
string targetAddress = "59.337017307552195, 18.05017354381474";
await JS.InvokeVoidAsync("initNavigation", origin, targetAddress);
}
else
{
// Handle permission denied scenario
Console.WriteLine("Location permission denied");
}
}
}