Stormdamage
Stormdamage

Reputation: 389

Google Maps v3 directionsRenderer.setMap(null) not working to clear previous directions

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

Upvotes: 2

Views: 10760

Answers (1)

Mohayemin
Mohayemin

Reputation: 3870

This is because you are initializing a new directionsRenderer in every call of the function.

Make the directionsRenderer little more global. and first setMap(null), then initialize, then setMap(googleMap)

Like this:

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

Upvotes: 8

Related Questions