【问题标题】:How can I clear routes on google.map?如何清除 google.map 上的路线?
【发布时间】:2017-01-19 18:39:45
【问题描述】:

当我加载多个路由时,不会删除前一个路由。 许多人说将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!');
            }
        });
    });

【问题讨论】:

  • 你在 JS 控制台看到了什么错误?
  • 在控制台显示任何错误。
  • 这是什么意思?

标签: javascript angularjs google-maps-api-3


【解决方案1】:

因为通过将后一个变量分配给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       

});

【讨论】:

  • 在这种情况下显示此错误:“google is not defined”
  • 这是一个常见的错误,在库加载后使用iniMap回调更新全局引用
  • 我该怎么做?
  • @HugoLeite,请参阅更新的答案。我不是 AngularJS 人,但同样的原则也适用于纯 JavaScript。
猜你喜欢
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 2022-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
相关资源
最近更新 更多