Google 地图标记 Url

Google Map Markers With Url

我真的无法理解javascript,我知道这应该是一个非常简单的问题,但我坚持了.. 我有一个带有多个标记的 google 地图,我添加了每个标记并且工作完美,但我想给它们 links。我的位置数组就像;

['http://website.com',36.598900,35.202094,'1']

我将 [1] 和 [2] 用作纬度,但我想将 [0] 用作 link。我的循环工作完美,但每个标记的 link 都会转到最后一项的 link

这是我的循环

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: image,
    url: locations[i][0],
  });

  google.maps.event.addListener(marker, 'click', function() {
    window.location.href = marker.url;
  });

}

我哪里弄错了?

1/需要在marker = new google.maps.Marker({

前加上var

因为,您现在使用 marker 作为每次迭代都会覆盖的全局变量。

2/ 无论如何,最好的做法是将所有标记保存为对象属性。我们称此对象为:mk,那么您的标记将为 mk.marker0mk.marker1、...等等。

var mk={}; // this is nameSpace to save all markers
locations.map((loc,i)=>{
    mk['marker'+i] = new google.maps.Marker({
      position: new google.maps.LatLng(loc[1], loc[2]),
      map: map,
      icon: image,
      url: loc[0],
    });
    return mk['marker'+i];
}).forEach((marker)=>{
              google.maps.event.addListener(marker, 'click', function() {
                  window.location.href = marker.url;
             });    

 })