【问题标题】:InfoWindows are opening Without ClickInfoWindows 无需点击即可打开
【发布时间】:2014-11-29 05:54:03
【问题描述】:

我正在使用 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));
}

}

【问题讨论】:

  • 因为您正在立即执行点击回调函数,而不是传递对它的引用

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


【解决方案1】:

问题在于您的代码在设置点击处理程序的最后。它试图以一种奇特的方式设置闭包,但它无意中使用了立即调用函数表达式 (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 );
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多