我目前正在实施一个物流应用程序,并在那里集成了谷歌地图。现在我需要在应用程序中显示 Google 地图导航。
我添加了一个名为 Navigation.razor 的新页面,并将其用作主组件中的子组件。
目前,地图仅显示给定两个位置之间的路径。我该如何修改它以显示导航?
<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");
}
}
}
有没有办法以某种方式显示逐向导航?
有多种方法您可以尝试。
1.如果你想在你的应用程序中完全实现导航,你可以使用Google Maps API和Google Directions API的组合。
Google 地图 API:Google 地图 API。
方向 API:方向 API
2.将您要导航的位置的纬度和经度发送到设备的地图应用程序。然后它将打开设备的地图应用程序并绘制位置。用户可以使用该应用程序做任何他们想做的事情。