2010-11-24 149 views
5

我已经创建了一个标记数组。我使用这些标记阵列来聆听'点击'并将标记放置在Google地图上,并创建函数以“清除所有标记”,“重新显示所有标记”和“删除所有标记”。如何在谷歌地图上一次删除一个标记

问题是,我如何以一种能够清除或删除一次一个标记的方式执行此操作?原因是因为如果我碰巧无意中划到了一个我不想要的地方,而且我想清除/删除它,我无法做到这一点。如果我是清除/删除特定的标记,那我以前绘制的将被清除标记其余/删除,以及...

我的代码:

//Initialize the map 
function initialize() { 
    var myLatlng = new google.maps.LatLng(2,110); 
    var myOptions = { 
     zoom: 3, 
     center: myLatlng, 
     mapTypeId: google.maps.MapTypeId.HYBRID 
    }; 

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    infowindow = new google.maps.InfoWindow({ 
     content: "loading..." 
    }); 
} 

function changeForm(the_form) { 
    window.location = the_form; 
} 


//Listen for click 
function marker() { 
    google.maps.event.addListener(map, 'click', function(event) { 
     addMarker(event.latLng); 
    }); 
} 

// Place markers in by click 
function addMarker(location) { 
    marker = new google.maps.Marker({ 
     position: location, 
     map: map, 
     title:"Specified Location", 
     icon: 'images/greenPoint.png' 
    }); 
    markersArray.push(marker); 
} 

// Deletes all markers in the array by removing references to them 
function deleteOverlays() { 
    if (markersArray) { 
     for (i in markersArray) { 
      markersArray[i].setMap(null); 
     } 
     markersArray.length = 0; 
    } 
} 

// Removes the overlays from the map, but keeps them in the array 
function clearOverlays() { 
    if (markersArray) { 
     for (i in markersArray) { 
      markersArray[i].setMap(null); 
     } 
    } 
} 

// Shows any overlays currently in the array 
function showOverlays() { 
    if (markersArray) { 
     for (i in markersArray) { 
      markersArray[i].setMap(map); 
     } 
    } 
} 

回答

4

当你创建你的标记,而不是将它们全部推到列表markersArray上,您可以根据它们的Lat/Lng(或更好的事件,某种id)来存储它们,然后在每个标记上设置一个事件处理程序,以将其本身从标记列表中移除当它被点击时。

我不知道,如果你可以存储任意信息与google.maps.Marker对象,但你总是可以创建自己的对象,有一个ID和google.maps.Marker对象作为其成员:

function myMarker(id, location) { 
    this.id = id; 
    this.marker = new google.maps.Marker({...}); 
} 

然后markersArray[id] = new myMarker(myId, myLocation)将允许您存储所有基于其任意ID的标记。然后,您可以指定我在this.marker上描述的处理程序,以从markersArray和地图中删除自己。

另一种方式来做到这一点是基于他们的纬度/ LNGS来存储您的标记,所以你markersArray将节省沿着线的标记:

markersArray[location.lat][location.lng] = new google.maps.Marker({...}); 

然后你就可以用你的事件处理程序单击时抓住标记的lat/lng,然后将其从阵列中移除并映射。

让我知道你是否需要更多的细节。