0

我的谷歌地图网络应用程序出现问题,我正在尝试向地图添加标记,然后当用户单击该标记时,会出现标记的名称。

我将有关每个标记的信息存储在一个数组中,如下所示:

var citymap = {};
      citymap['edinburgh'] = {
        center: new google.maps.LatLng(55.934120, -3.226569),
        population: 284,
        image:clueImage,
        color: '#ff0000',
        elementId:'clue1'
      };
       citymap['clue2'] = {
        center: new google.maps.LatLng(55.970783, -3.164594),
        population: 284,
        image:clueImage,
        color: '#ff0000',
        elementId:'clue2'
      }
         citymap['clue4'] = {
        center: new google.maps.LatLng(55.939583, -3.202092),
        population: 284,
        image:clueImage,
        color: '#ff0000',
        elementId:'clue3'
      }
         citymap['clue9'] = {
        center: new google.maps.LatLng(0, 0),
        population: 284,
        image:clueImage,
        color: '#ff0000',
        elementId:'clue1'
      }

然后我循环遍历数组并将标记添加到地图:

for (var city in citymap) {

       var playerMarker = new google.maps.Marker({
      position: citymap[city].center,
      map: map,
      icon: citymap[city].image
      });

      google.maps.event.addListener(playerMarker, "click", function() {
      var elementConnected = citymap[city].elementId;
     console.log(elementConnected);
    });

        }

一切都按预期工作,但是当我单击任何标记时,它们都会记录数组中最后一个标记的值。我知道这是因为那是循环完成的地方,但我想不出一种方法来完成这项工作。

帮助将非常有帮助!

4

1 回答 1

0

我认为这是人们在 Javascript 中普遍存在的“关闭”问题。有人可能会给出更好的方法,但我认为你需要这样的东西:

google.maps.event.addListener(playerMarker, "click", (function() {
    return function () {
        var elementConnected = citymap[city].elementId;
        console.log(elementConnected);
    };
})(city));

或者如果可能的话,取决于您在click活动中所做的其他事情,也许是这样的:

google.maps.event.addListener(playerMarker, "click", (function(elementId) {
    return function () {
        var elementConnected = elementId;
        console.log(elementConnected);
    };
})(citymap[city].elementId));
于 2012-11-20T14:22:39.263 回答