InfoWindows正在打开No Click

时间:2014-11-29 05:54:03

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

我正在使用googlemaps api在地图上放置一些标记。但是出于某种原因我的infoWindows为所有标记,默认情况下打开即使没有点击。我不知道为什么会发生这种情况,我尝试在其他地方搜索下面的代码看起来没问题(至少对我来说)

function PoplatePoints(data) {
var output = new google.maps.LatLng(25.4486, 78.5696);
var mapOptions = {
  center: output,
  zoom: 7
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);

//var contentString = [];
//  var infowindow = [];
for (var i = data.length - 1; i >= 0; i--) {

  var contentString = 'Hello This is me';

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

  var  icon_new = "/static/beyond/img/Green.png";

  var marker = new  google.maps.Marker({
    position: new google.maps.LatLng(data[i].lat, data[i].long),
    map: map,
    icon: icon_new
  });

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

}

1 个答案:

答案 0 :(得分:0)

问题在于你的代码最后设置了点击处理程序。它试图以一种奇特的方式设置一个闭包,但是它无意中使用了一个立即调用的函数表达式(IIFE)。请注意“立即调用”部分。代码没有将函数 reference 传递给addEventListener,它实际上是首先执行函数。

你确实需要一个闭包,但有一个更简单的方法来设置它。我会这样做:

function PopulatePoints( data ) {
    var output = new google.maps.LatLng( 25.4486, 78.5696 );
    var mapOptions = {
        center: output,
        zoom: 7
    };

    var map = new google.maps.Map(
        document.getElementById('map-canvas'),
        mapOptions
    );

    for( var i = 0;  i < data.length;  ++i ) {
        AddPoint( data[i] );
    }

    function addPoint( point ) {
        // TODO: This string will probably be passed in as a
        // property of the point variable
        var contentString = 'Hello This is me';

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

        var icon_new = "/static/beyond/img/Green.png";

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng( point.lat, point.long ),
            map: map,
            icon: icon_new
        });

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