javascript - 谷歌地图信息窗口在不同标记上给出相同的结果

标签 javascript google-maps-api-3

有以下问题,信息窗口在不同的标记上给出相同的结果。 当我在 geocoder.geocode 函数外部调试时,它显示正确的信息,但内部始终相同(第一个)。 suppid 部分是当我调试其中的 i 变量时显示正确的值。

var optionMap = {
            zoom: 16,
            MapTypeId: google.maps.MapTypeId.ROADMAP,
            panControl: false,
            zoomControl: false,
            mapTypeControl: false,
            scaleControl: false,
            streetViewControl: false,
            overviewMapControl: false
        };

        var map = new google.maps.Map(document.getElementById('map'), optionMap);

        var geocoder = new google.maps.Geocoder();

        var latlngbounds = new google.maps.LatLngBounds();

        var icon = new google.maps.MarkerImage('images/gm_pin.png',
        new google.maps.Size(20, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34));

        for(var i = 0; i < arrAddress.length; i++) {

            var address = arrAddress[i];

            var html_title = "<div class='info'><h4>" + address + "</h4></div>";

            geocoder.geocode({
                'address': address
            }, function (results, status) {

                 if(status == google.maps.GeocoderStatus.OK) {


                    var marker = new google.maps.Marker({
                        map: map,
                        icon: icon,
                        html: html_title, 
                        position: results[0].geometry.location
                    });

                    var contentString = '';

                    var infoWindow = new google.maps.InfoWindow({
                        content: contentString

                        });

                    google.maps.event.addListener(marker, 'mouseover', function() {  
                        infoWindow.setContent(this.html);
                        infoWindow.open(map, this);
                    });

                    google.maps.event.addListener(marker, 'mouseout', function() {  
                        infoWindow.close(map, this);
                    });

                    latlngbounds.extend(results[0].geometry.location);

                    if(i == arrAddress.length) {
                        map.fitBounds(latlngbounds);
                    }

                    google.maps.event.trigger(map, 'resize')
                }
            });
        }

最佳答案

调用Geocoder.geocode(请求,回调) is asynchronous 。当服务器响应时,回调函数被调用。通常到这个时候,for循环就已经结束了。这可以得到您所描述的确切结果,例如每个标记具有相同的内容,因为标记是在循环完成后发生的回调中创建的,因此它将使用 html_title 中的最后一个值。

解决这个问题的方法是在循环内创建一个闭包,它将“捕获”循环内的变量html_title。这样,回调将使用 html_title 的正确值。

JavaScript 中典型的显式闭包如下所示:

// Wrap a function in () and immediately call it with another ()
// Pass in the arguments in the second () 
// This causes them to be 'captured' inside the function
(function(args) { /* Do something with args */ })("Hello", 42);

在您的代码中,闭包需要在循环期间捕获地址:

for(var i = 0; i < arrAddress.length; i++) {
  var address = arrAddress[i];
  var html_title = "<div class='info'><h4>" + address + "</h4></div>";

  (function(address, title) {
    // Inside the closure, we can use address and html_title
    geocoder.geocode({'address': address /* captured */}, function (results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          icon: icon,
          html: title, /* captured */ 
          position: results[0].geometry.location
        });

        var contentString = '';
        var infoWindow = new google.maps.InfoWindow({
          content: contentString
        });

        // ...
      }
    });
  })(address, html_title); // <- Call function, pass the vars to be captured 
}

关于javascript - 谷歌地图信息窗口在不同标记上给出相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960893/

相关文章:

javascript - 根据属性中指定的大小动态更改图像

javascript - 使用 JSON 序列化图论树的解决方法?

javascript - 使用 addEventListener 注册的事件存储在哪里?

google-maps - flutter + 谷歌地图 : How to animate the camera to target location

javascript - 隐藏标记显示在 google map api v3 中的群集图标中

jquery - 谷歌地图消失

javascript - 消息关闭后不会再次显示

javascript - 有时它说密码无效,而实际上它是有效的

javascript - 嵌入式 Google map 图 block 在缩放之前无法在 Firefox 第二页加载中加载

javascript - 未捕获的类型错误 : Cannot read property 'latitude' of undefined