单击标记时,地理编码器将返回先前存储的值

时间:2012-07-18 14:25:47

标签: javascript google-maps-api-3

我正在使用google map api v3(javascript)实现地理编码器。我正在添加多个标记,当我点击标记时,我希望相应的地址进入信息窗口。但是当我点击标记时,最初地址的默认值(根据代码地理位置不可用!)即将到来,当我点击第二个标记时,它具有先前点击的标记的地址。我正在附上这段代码。

    var addr=" Geo-Address Unavailable!";
    var geocoder = new google.maps.Geocoder();
    for(var i = 0; i < latLngs.length-1; i++){ //latLngs is the array of latlongs
       marker = new google.maps.Marker({
        position: latlng,
        id:markerId,
        icon: image,
        map: map,
        animation : google.maps.Animation.DROP,
             });
     }
     markers[markerId] = marker;
      var infowindow = new google.maps.InfoWindow({
                    content: "loading..."
                });
                google.maps.event.addListener(marker, "click", function () {
                    geocoder.geocode({'latLng': this.getPosition()}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                                addr = results[0].formatted_address;

                            }
                    });

                    infowindow.setContent(addr);
                    infowindow.open(map, this);
                });

1 个答案:

答案 0 :(得分:0)

地理编码是异步的。您必须在地理编码器的回调中使用返回的值。

发生了什么:

  1. 您向地理编码器发送请求。
  2. 您显示回复
  3. 响应来自地理编码器
  4. 您向地理编码器发送另一个请求
  5. 显示对第一个请求的响应
  6. 响应从地理编码器返回到第二个请求