2012-07-13 51 views
20

我有这个代码,我显示和设置我所有的标记。如何添加带有此代码的标记信息的弹出窗口?我在文本上添加了“i”变量,但它在所有标记弹出的“test-723”上设置,其中723是“i”变量的最后一个值。哪里不对?如何使用Google Maps API在标记上设置弹出窗口?

for (var i = 0; i < arraylng.length-1; i++) { 
    var marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(arraylng[i], arraylat[i]) 
    }); 
    var infowindow = new google.maps.InfoWindow({ 
    content: " " 
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent('test: ' + i + ''); 
    infowindow.open(map, this); 
    }); 
    markers.push(marker); 
} 

回答

38

首先,将环路条件更改为i < arraylng.length。现在它不捕获数组的最后一个元素。

JavaScript变量与函数作用域一起工作,因此您需要为每个标记侦听器调用一个函数来创建正确的变量引用。您可以使用匿名函数,as seen here,或定义一个函数用于创建点击收听:

多个信息窗口:

function makeInfoWindowEvent(map, infowindow, marker) { 
    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map, marker); 
    }); 
} 

最有可能你不会想不止一个信息窗口同时打开,因为点击关闭x是令人讨厌的。然后,你将只需要一个信息窗口对象,并设置为标记被点击的内容:

单信息窗口:内环路

... 
    var infowindow = new google.maps.InfoWindow(); 

    for (var i = 0; i < arraylng.length-1; i++) { 
    var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(arraylng[i], arraylat[i]), 
     map: map 
    }); 

    makeInfoWindowEvent(map, infowindow, "test" + i, marker); 

    markers.push(marker); 
    } 
} 

function makeInfoWindowEvent(map, infowindow, contentString, marker) { 
    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent(contentString); 
    infowindow.open(map, marker); 
    }); 
} 
+1

的解决方案,非常好,谢谢! – whoah 2012-07-15 09:50:44

+8

您的jsfiddle链接已过期。 – 2015-07-21 14:45:26

+0

链接不工作... -1 – 2016-08-12 13:40:45

0

这是因为变量i在循环不使用,但点击标记时 - 然后我等于最后一个索引+ 1 ... addListener是异步的,不同步的。

删除infowindow.setContent('test: ' + i + '');并用content: 'test: ' + i替换content: " "。这应该可以解决你的问题。

+0

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/做了很好的解释 – 2016-05-24 15:24:10

1
var marker = new google.maps.Marker({ 
       position: myLatLng, 
       .... 
       content: point[4] 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
      infowindow.setContent(this.content); 
      infowindow.open(map, this); 
      }); 

代码。这对我完美的工作。

相关问题