3

I am trying to clear previous directions from a Google Map. But when you do another search, the Polyline and markers from the previous search still show. I have tried using directionsRenderer.setMap(null), but it doesn't make any difference. Any ideas what I'm doing wrong?

(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();
    };
})();
4

1 回答 1

8

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();
    };
})();
于 2013-05-21T09:08:49.990 回答