我目前使用下面的代码将标记添加到地图中。我希望能够通过推送javascript命令随时删除任何一个。这可能吗?
离。放置5个标记..删除第3个,同时保留其他4个。
$('#map').show();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value +", " + document.getElementById("city").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
locationsall[counter] = new Array();
locationsall[counter][0] = address;
locationsall[counter][1] = lat;
locationsall[counter][2] = lng;
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker, i;
for (i = 0; i < locationsall.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsall[i][1], locationsall[i][2]),
map: map,
title: 'You are here!'
});
}
counter++;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}); }
编辑1:
}).text("Remove").click(function() {
var index2 = $tr2.index();
$("#locationDeals input[type='hidden']").each(function() {
this.name = this.name.replace(/\[(\d+)\]/, function(str2, number2) {
return "[" + (+number2 > index2 - 1 ? number2 - 1 : number2) + "]";
});
});
//locationsall[locations.indexOf(location)].setMap(null);
$tr2.remove();
locations.splice(locations.indexOf(location), 1);
return false;
}).appendTo($tdRemoveRow2);
答案 0 :(得分:2)
在for loop
之外定义Array
,其中包含所有添加的标记。例如。 allMarkers = []
创建标记后,在for loop
内,将其推入所述数组。例如。 allMarkers.push(marker)
如果您要删除第一个标记:allMarkers[0].setMap(null)
或第三个标记:allMarkers[2].setMap(null)
答案 1 :(得分:1)
是的,这是可能的。 Google Maps文档完全涵盖了这一点,包括代码示例等。本质上,标记是叠加而不是地图本身。您可以将这些叠加层放入数组中,然后使用setMap()
使其隐藏隐藏。
完整文档here。