【发布时间】:2015-05-22 03:25:48
【问题描述】:
我在使用谷歌地图标记时遇到了一些问题。我有一个包含 7 个位置的数组。当页面加载时,一个“for”循环遍历数组并将前四个位置作为标记放置在地图上。然后我想要发生的是能够单击“删除并添加标记”按钮,该按钮将运行一个函数(称为 addMarker2)以删除原始 4 个位置标记并将最后 3 个位置标记添加到地图中。
我已经测试了只添加最后 3 个标记的功能,它工作正常。但是,当我在添加最后 3 个标记之前添加代码以删除前 4 个标记时,它不再起作用了。我一直在寻找答案,我发现的几乎所有东西似乎都表明我做对了,虽然很明显我不是。
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(40, -95),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// create the map
var map = new google.maps.Map(mapCanvas, mapOptions);
// array of locations
var pins = [
['Cleveland',41.499321,-81.694359],
['Florence',34.195435,-79.762566],
['Knoxville',35.960638,-83.920739],
['Memphis',35.149532,-90.048981],
['Nashville',36.162664,-86.781602],
['Phoenix',33.448376,-112.074036],
['Toronto',43.653225,-79.383186]
];
// Loop through the array of locations & place each one on the map
for( i = 0; i < 4; i++ ) {
var position = new google.maps.LatLng(pins[i][1], pins[i][2]);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: 'http://i.imgur.com/FPiUErC.png',
title: pins[i]['0']
});
} // end of the for loop
function addmarker2() {
// remove the first four markers
for( i = 0; i < 4; i++ ) {
pins[i].setMap(null);
}
// add the last three markers
for( i = 4; i < 7; i++ ) {
var myPosition = new google.maps.LatLng(pins[i][1], pins[i][2]);
var marker = new google.maps.Marker({
position: myPosition,
map: map,
icon: 'http://i.imgur.com/FPiUErC.png',
title: pins[i][0]
});
} // end of for loop
} // end of addmarker2 function
$("#mysubmit").click(addmarker2);
我使用 setMap(null) 的方式一定有问题。 I have a jsfiddle of the code. 一开始它不会起作用,但是如果你注释掉试图删除前 4 个标记的“for”循环,那么它将成功添加最后 3 个。我只需要它来做这两件事。
【问题讨论】:
-
您需要在marker 上设置地图,而不是您存储在pins 数组中的数据。我updated your fiddle
-
太棒了!感谢您的帮助。
标签: javascript google-maps google-maps-markers