简体   繁体   English

如何在Google Maps API3中删除单个标记

[英]How to remove individual markers in Google maps api3

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. 我知道还有其他解决方案,但是它们都不适合我的情况,因为我的标记位于函数中,并且标记是从外部XML文件创建的,如果您更改坐标,则可以在该当前位置添加标记。 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);
         }

    }
}
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 概念证明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM