1

我必须在运行时在谷歌地图上创建几个标记。

它们的初始位置是随机定义的。

创建它们后,如何更改其中一些的位置?新位置也是随机定义的。

我确实尝试过

marker1.setPosition(pt);

...但是,我遇到了错误

marker1 is not defined

我想这个问题是在创建地图的那一刻没有定义marker1......类似的东西。

你能帮我解决这个问题吗?

ps 创建的标记数量没有限制。

更新标记是通过以下方式创建的:

function addNewMarker( locationsTotal ) {

if (document.getElementById("lon1").value == '') document.getElementById("lon1").value = '19';
if (document.getElementById("lat1").value == '') document.getElementById("lat1").value = '45';

var parliament = (map.getCenter());

var newMarker = 'marker' + locationsTotal;
newMarker = new google.maps.Marker({
  name:newMarker,
  id:newMarker,
  map:map,
  draggable:true,
  animation: google.maps.Animation.DROP,
  position: parliament, 
  icon: 'img/pin.png'
});

google.maps.event.addListener(newMarker, "dragend", function() {
  var center = newMarker.getPosition();
  var latitude = center.lat();
  var longitude = center.lng();
  var newLon = 'lon' + locationsTotal;
  var newLat = 'lat' + locationsTotal;
  document.getElementById(newLon).value = longitude;
  document.getElementById(newLat).value = latitude;
});

}
4

1 回答 1

3

如您所见newMarker,仅在addNewMarker功能范围内可见。您需要将标记存储在全局范围内可见的数组中。例如:修改你的功能:

var allMarkers = [];
function addNewMarker( locationsTotal ) {
   //.... skip
  allMarkers.push(newMarker);
}

您的所有标记现在都存储在一个数组中,以便您可以操作它们。

要按名称添加功能访问标记:

function getMarker(name) {
  for (k in allMarkers)
     if (allMarkers[k].name == name) return allMarkers[k];
  return null;
}
于 2012-05-17T10:37:02.817 回答