Google Maps v3 directionsRenderer.setMap(null)无法清除之前的路线

时间:2013-05-21 09:04:22

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

我正在尝试从Google地图中清除以前的路线。但是当您进行另一次搜索时,仍会显示上一次搜索中的折线和标记。我尝试过使用directionsRenderer.setMap(null),但它没有任何区别。我有什么想法吗?

(function () {    
    Maps.Directions = function(googleMap, data, options) {
        var directionsService = new google.maps.DirectionsService(),
            directionsRenderer = new google.maps.DirectionsRenderer();

        function getDirections() {
            directionsService.route(data.request, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    directionsRenderer.setDirections(response);
                }
            });
        }
        directionsRenderer.setMap(null);
        directionsRenderer.setMap(googleMap);
        getDirections();
    };
})();

1 个答案:

答案 0 :(得分:7)

这是因为您在函数的每次调用中初始化一个新的directionsRenderer

使directionsRenderer更加全球化。然后先setMap(null),然后初始化,然后setMap(googleMap)

像这样:

(function () {   
    var directionsRenderer;
    Maps.Directions = function(googleMap, data, options) {
        if(directionsRenderer){
            directionsRenderer.setMap(null);
        }
        var directionsService = new google.maps.DirectionsService();

        directionsRenderer = new google.maps.DirectionsRenderer();
        function getDirections() {
            directionsService.route(data.request, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    directionsRenderer.setDirections(response);
                }
            });
        }

        directionsRenderer.setMap(googleMap);
        getDirections();
    };
})();