请你看一下this Link并告诉我为什么我无法从地图中删除标记?我收到此错误消息:
未捕获的TypeError:对象[object Array]没有方法'setMap'
代码:
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$( "#trg" ).click(function() {
$.ajax({
// type: "POST",
url: 'SO_20131215_data.json.txt',
dataType: 'json',
success: function(data){
locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
locations.push(Array(data.markers[p].latitude,data.markers[p].longitude));
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude,data.markers[p].longitude),
map: map,
title:"marker "+p
});
}
},
error: function (xhr,status,errorStr) {
alert("status="+status+", error="+errorStr);
}
});
});
function removeMarkers() {
for (i = 0; i < locations.length; i++) {
locations[i].setMap(null)
}
}
$('#remover').click(function () {
removeMarkers();
});
答案 0 :(得分:1)
function removeMarkers() {
for (i = 0; i < locations.length; i++) {
if(locations[i])
locations[i].setMap(null)
}
}
还有一件事,在ajax成功函数中:
for (p = 0; p < data.markers.length; p++) {
//locations.push(Array(data.markers[p].latitude,data.markers[p].longitude));
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude,data.markers[p].longitude),
map: map,
title:"marker "+p
});
locations.push(marker);
}
答案 1 :(得分:0)
在调试代码时,似乎你指的是地图的位置(纬度/经度),如
locations[i].setMap(null) //WRONG
哪个错了。使用 setMap
的正确方法是使用Google地图的标记
function removeMarkers() {
for (i = 0; i < marker.length; i++) {
marker[i].setMap(null); //refer marker
marker[i] = null; //if you wish to delete the marker
}
}
仅供参考:在您的代码中,marker
变量是本地范围,因此请尝试将其更改为全局范围。