我正在尝试使用 ionic 4 中的 Google Map JS 版本使用路线构建实时跟踪。我想要实现的是为用户提供从源到目的地的路线,并在用户选择其他新路径时更新路线比谷歌提供的。源是用户,目的地是地图中的某个点。
如果用户使用更改提供的路径,我可以绘制路线并更新它
startNavigation(){
this.geolocation.getCurrentPosition({ enableHighAccuracy: true })
.then((position) => {
this.userPosition = position;
this.userVehicleMarker = new google.maps.Marker({
map: this.map,
position: { lat: position.coords.latitude, lng: position.coords.longitude },
icon: this.vehicleIcon
});
this.addInfoWindow(this.userVehicleMarker, 'me')
this.watchVehicle = this.geolocation.watchPosition({ enableHighAccuracy: true })
.subscribe(async (pos) =>
{
// Calling the redraw function on every 25 meters distance travelled
this.drawRouteFromVehicleToDestination(pos.coords.latitude, pos.coords.longitude)
}
}, (err: PositionError) => {
// alert(err.message)
console.log("error : " + err.message);
});
})
)
drawRouteFromVehicleToDestination(lat, lng) {
let _self = this;
let directionsService = new google.maps.DirectionsService;
let directionsRenderer = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "#428BE8",
strokeWeight: 2
},
suppressMarkers: true,
preserveViewport: true
});
directionsRenderer.addListener('directions_changed', function () {
let _data = directionsRenderer.getDirections();
let _newData = _data['routes'][0]['legs'][0]
console.log(_newData)
});
directionsService.route({
origin: { lat: lat, lng: lng},
destination: { lat: 27.673586, lng: 85.435131},
travelMode: 'DRIVING',
optimizeWaypoints: true,
provideRouteAlternatives: false,
avoidTolls: true,
}, (res, status) => {
if (status == 'OK') {
directionsRenderer.setDirections(res);
directionsRenderer.setMap(this.map);
} else {
console.warn(status);
}
});
}
但问题是,它向谷歌 API 发送了大量请求,这看起来不像是一种实用的方法。
我应该遵循其他任何方法来跟踪路线并根据用户位置更改更新它并最小化谷歌 ping?
预先感谢您的帮助。