如何在谷歌地图上清除路线



当我加载多个路由时,不会删除以前的路由。很多人说要把directionsDisplay.setMap设置为null,但这行不通。看起来路线在地图上而不是directionsDisplay.这是我的代码不起作用:

NgMap.getMap('mapShop').then(function(map) {
    $scope.googleMaps = map;
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var directionsService = new google.maps.DirectionsService();
                    directionsDisplay.setMap(null);
                    directionsDisplay.setDirections(null);
                    directionsDisplay.setMap($scope.googleMaps);
    // get geolocation for center map and marker
    NavigatorGeolocation.getCurrentPosition().then(function(position) {
        $scope.latitude = $routeParams.latitude;
        $scope.longitude = $routeParams.longitude;
        $scope.urlLocalCard = "http://maps.apple.com/?daddr=" + $routeParams.latitude + "," + $routeParams.longitude + "&saddr=" + position.coords.latitude + "," + position.coords.longitude + "&ll=" + $routeParams.latitude + "," + $routeParams.longitude + "&z=10&t=s";
        var request = {
            origin: position.coords.latitude + ',' + position.coords.longitude,
            destination: $routeParams.latitude + ',' + $routeParams.longitude,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            } else {
                alert('Google route unsuccesfull!');
            }
        });
    });

因为通过将后一个变量分配给google.maps.DirectionsRenderer的新实例,您将丢失了对旧directionsDisplay的引用。将directionsDisplaydirectionsService移动到全局范围。

var directionsDisplay,
    directionsService;
// Update global reference upon Google map loads
function initMap(){
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    directionsService = new google.maps.DirectionsService();
}
NgMap.getMap('mapShop').then(function(map) {
       $scope.googleMaps = map;
       directionsDisplay.setMap(null);
       directionsDisplay.setDirections(null);
       // rest of code       
});

最新更新