karim karim
karim karim

Reputation: 91

How to delete a direction markers in google map API

I want to delete a google map direction markers after a search without reloading the page. I've made an example but its not working :

//First of all testing if there is already a direction on the map

if(directionsService != null) 
{
  directionsService.setMap(null);
  directionsService = null;
}

  //Then display the new one

  var origin = $('#de').val();
  var destination = $('#en').val();
  var request = {
        origin      : origin,
        destination : destination,
        travelMode  : google.maps.DirectionsTravelMode.DRIVING 
    }

    var directionsService = new google.maps.DirectionsService(); 
            directionsService.route(request, function(response, status){ 
                if(status == google.maps.DirectionsStatus.OK){
                    direction.setDirections(response); 
                    showSteps(response);
                }
    });

all this code is on a function called by a click event

<button id="envoyer" id=="env" onclick="javascript:c()">Send</button>   

so any one have an idea thanks !

Update

function showSteps(directionResult) {
  var markerArray = [];
  var myRoute = directionResult.routes[0].legs[0];

  for (var i = 0; i < myRoute.steps.length; i++) {
    var marker = new google.maps.Marker({
      position: myRoute.steps[i].start_location,
      map: map
    });
    attachInstructionText(marker, myRoute.steps[i].instructions);
    markerArray[i] = marker;
  }
}

Upvotes: 0

Views: 1155

Answers (1)

GNi33
GNi33

Reputation: 4509

When clearing the itinerary, using directionsService.setMap(null); you will have to remove the MapMarkers, which aren't directly connected to the Direction - Service, seperately too.

You have already stored them in markerArray inside of your showSteps - function, so you would need to move this variable out of the function into an outer scope or let the function return it to be able to access it.

By doing this, you can simply loop over the markerArray and call .setMap(null) on each stored Marker, thus removing them from the map.

var markerArray = [];

function showSteps(directionResult){

// your code

}

//function to remove MapMarkers
function removeMapMarkers(){

    for(var i=0; i<markerArray.length; i+=1){
        markerArray[i].setMap(null)
    }

    markerArray = [];

}

Upvotes: 2

Related Questions