How to remove individual markers in Google maps api3

96 views Asked by At

I know there are other solutions out there but none of them apply to my situation that easily because my markers are in a function and a marker is created from an external XML file where if you change the coordinates you add a marker in that current position. here is my code for the markers

var lastCoordinates={};
var polyline = new google.maps.Polyline({map:map})
var path = [];
function gotdata(){

    if (xmlhttp.readyState == 4){

        var d = xmlhttp.responseXML.documentElement 
            //innerHTML shouldn't work for XML-Nodes
            y = d.getElementsByTagName("y")[0].textContent,
            x = d.getElementsByTagName("x")[0].textContent,
            h = [x,y].join('_');
        if(lastCoordinates[h]){
          return;
        } 

        lastCoordinates[h]= new google.maps.Marker({
                              position: new google.maps.LatLng(x,y),
                              map: map,
                              title: 'YAY'
                            });
         path.push(lastCoordinates[h].getPosition());
         if (path.length >= 2) {
           // display the polyline once it has more than one point
           polyline.setMap(map);
           polyline.setPath(path);
         }

    }
}
1

There are 1 answers

2
geocodezip On
function gotdata() {
  if (xmlhttp.readyState == 4){
    count++;
    // var d = xmlhttp.responseXML.documentElement 
    //innerHTML shouldn't work for XML-Nodes
    y = count * 0.01; // d.getElementsByTagName("y")[0].textContent,
    x = count * 0.01; //d.getElementsByTagName("x")[0].textContent,
    h = [x, y].join('_');
    if (lastCoordinates[h]) {
        return;
    }

    lastCoordinates[h] = new google.maps.Marker({
        position: new google.maps.LatLng(x, y),
        map: map,
        title: 'YAY'
    });
    rightclickableMarker(lastCoordinates[h],h);    
    map.panTo(lastCoordinates[h].getPosition());
    path.push(lastCoordinates[h].getPosition());
    if (path.length >= 2) {
        // display the polyline once it has more than one point
        polyline.setMap(map);
        polyline.setPath(path);
    }
  }
}
function rightclickableMarker(marker, h) {
    google.maps.event.addListener(marker, 'rightclick', function(evt) {
        if(lastCoordinates[h] && lastCoordinates[h].setMap){
          lastCoordinates[h].setMap(null);
          delete marker;
        } 
    });
}

proof of concept fiddle