如何删除Google maps api3中的单个标记

时间:2015-06-08 09:10:10

标签: javascript google-maps google-maps-api-3 coordinates google-maps-markers

我知道还有其他解决方案,但它们都不适用于我的情况很容易,因为我的标记在一个函数中,并且标记是从外部XML文件创建的,如果你更改坐标,你在其中添加一个标记当前位置。这是我的标记代码

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 个答案:

答案 0 :(得分:0)

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