Ken*_*nC. 5 javascript google-maps
我创建了一系列标记.我使用这些标记来听取"点击"并将标记放在谷歌地图上,以及创建"清除所有标记","重新显示所有标记"和"删除所有标记"的功能.
问题是,我如何以一种能够一次清除或删除一个标记的方式执行此操作?原因是因为如果我偶然地在一个我不想要的地方进行策划,并且我想清除/删除它,我就无法做到.如果我要清除/删除该特定标记,我之前绘制的其他标记也将被清除/删除...
我的代码:
//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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您创建标记时,您可以根据纬度/经度(或者更好的事件,某种 id)存储它们,而不是将它们全部推送到列表标记数组上,然后在每个标记上设置一个事件处理程序以删除自身单击时从标记列表中。
我不确定您是否可以使用 google.maps.Marker 对象存储任意信息,但您始终可以创建自己的对象,该对象具有 ID 和 google.maps.Marker 对象作为其成员:
function myMarker(id, location) {
this.id = id;
this.marker = new google.maps.Marker({...});
}
Run Code Online (Sandbox Code Playgroud)
然后markersArray[id] = new myMarker(myId, myLocation)将允许您根据任意 ID 存储所有标记。然后,您可以分配我所描述的处理程序,this.marker以将自己从地图中删除markersArray。
另一种方法是根据纬度/经度存储标记,因此您的标记数组将按照以下方式保存标记:
markersArray[location.lat][location.lng] = new google.maps.Marker({...});
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用事件处理程序在单击时获取标记的纬度/经度,并将其从数组中删除并以这种方式绘制地图。
如果您需要更多详细信息,请告诉我。