2

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();
    };
})();
Stormdamage
  • 389
  • 1
  • 5
  • 16

1 Answers1

7

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();
    };
})();
Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • If you wanted to have multiple routes on screen at once, is there a way to check if the route already exists before drawing the exact same route over it? – Jason Silver Jul 22 '15 at 15:45
  • what worked for me was the following comment `initializing a new directionsRenderer in every call of the function`. Thanks! – Kiran Nov 12 '15 at 08:17
  • Getting Maps undefined error in angular project. Any help will be appreciable . – Pullat Junaid Mar 26 '19 at 09:44