显示循环最后值的谷歌地图信息窗口

Google Map infowindow showing last value of loop

本文关键字:信息 信息窗 窗口 谷歌地图 循环 最后 显示      更新时间:2023-09-26

我使用for循环来显示标记和信息窗口。但是信息窗口只显示循环的最后一个值。

这是我使用的代码。

  function initialize()
    {
        try
        {
            var geocoder;
            var map;
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(41.511770, -72.809520);
            var mapOptions = {              
              center: latlng,
               zoom: 9,
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP 
            }
            map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
            var markers = JSON.parse('[{"address":"40C Leslie Road,Bridgeport,CT","Description":"Bridgeport - 82 Unit Community"},{"address":"56 Ironwood Road,West Hartford,CT","Description":"West Hartford - 45 Unit Community"}]');
            var infoWindow = new google.maps.InfoWindow();
           // var address;
            for (i = 0; i < markers.length; i++)
            {
                var address = markers[i];               
                geocoder.geocode({ 'address': address.address }, function (results, status)
                {
                    if (status == google.maps.GeocoderStatus.OK) 
                    {
                        //map.setCenter(results[0].geometry.location);
                        var marker = new google.maps.Marker({
                            map: map,
                            icon:'Images/pin.png',
                            position: results[0].geometry.location
                        });
                        google.maps.event.addListener(marker, "click", function (e)
                        {                       
                            infoWindow.setContent("<div style='border:0px solid red;height:auto;;width:auto;'>" + address.Description + "</div>");
                            infoWindow.open(map, marker);
                        });
                    }
                    else {
                        //alert("Geocode was not successful for the following reason: " + status);
                    }
                });
              //  map.setCenter(new google.maps.LatLng(41.511770, -72.809520))
            }
        }
       catch (ex)
        {
            alert(ex.message);
        }     
    }
    google.maps.event.addDomListener(window, "load", initialize);

请帮帮我。

谢谢,Venkat .

问题是geocoder.geocode是一个异步函数。换句话说,在请求完成对值的检索之前,执行就离开了for循环。因此,您将获得相同的地址值,因为它是for循环结束时的最后一个值,并且您将所有内容都放置到相同的var address = ...变量中。

要解决这个问题,您需要将geocoder.geocode请求包装在自动执行的匿名函数中。因此,您的代码可以正常工作,因为var address = ...与请求一起定义在它自己的作用域中。请看下面的例子:

...
// Start of self-executing anonymous function
(function() {
var address = markers[i];  
...

:

...
// End of self-executing anonymous function
})();
//  map.setCenter(new google.maps.LatLng(41.511770, -72.809520))
...

JS FIDDLE示例(记住激活你的图标图像,我在代码中禁用了它。)

进一步阅读,我推荐自执行匿名函数

欢呼。