Google Maps API V3 infoWindow - 显示相同内容的所有infoWindows

时间:2011-02-04 11:08:28

标签: javascript google-maps google-maps-api-3 infowindow

在我的页面中,纬度,经度和信息窗口内容存在于名为obj的对象数组中。

所以如果我需要第一个对象的属性的纬度,我可以调用obj [0] .latitude。

每个对象的infoWindow内容存储在obj [i] .text。

我正在使用以下循环来遍历lat& long值并显示标记和infoWindows。

  for (x=1; x<=obj.length; x++)
  {
      var latlng1 = new google.maps.LatLng(obj[x].latitude, obj[x].longitude);

var marker2 = new google.maps.Marker({ position : latlng1, map : map, icon : prevIcon }); infowindow = new google.maps.InfoWindow(); info = obj[x].text; google.maps.event.addListener(marker2, 'mouseover', function() { infowindow.setContent(info); infowindow.open(map, this); });

}

var marker2 = new google.maps.Marker({ position : latlng1, map : map, icon : prevIcon }); infowindow = new google.maps.InfoWindow(); info = obj[x].text; google.maps.event.addListener(marker2, 'mouseover', function() { infowindow.setContent(info); infowindow.open(map, this); });

上面的代码有效,但所有的infoWindows都显示了最后一个obj [i] .text的内容。

如何将特定infoWindow(obj [x] .text)的infoWindow内容仅与该infoWindow实例相关联?

如果有人可以在不使用jQuery或任何其他外部库的情况下指出解决方案,那会更好。

谢谢,

2 个答案:

答案 0 :(得分:4)

应该让你走很远的路。

function attachMarker( data ) {

    var latLng = new google.maps.LatLng( data.latitude, data.longitude );

    var marker = new google.maps.Marker({
        position : latLng,
        map      : map, // global variable?
        icon     : prevIcon // global variable?
    });

    google.maps.event.addListener(marker, 'mouseover', function() {
       infowindow.setContent( data.text );
       infowindow.open(map, this);
    });

    // add marker here.

}

// afaik, you only need 1 instance of InfoWindow if you only change content.
var infowindow = new google.maps.InfoWindow();

var i = obj.length;
while ( i-- ) {
    attachMarker( obj[ i ] );
}

答案 1 :(得分:0)

BGerrissen上面的评论帮了很多忙。

我设法在info变量上实现了函数闭包。

以下Google网上论坛帖子介绍了如何使用。

https://groups.google.com/group/google-maps-api-for-flash/browse_thread/thread/befeb9bf2d1ebcc9

谢谢大家:)

相关问题