geocoder is returning previously stored value when

2020-02-15 08:30发布

I'm implementing geocoder using google map api v3 (javascript). I'm putting mutiple markers and when i click on marker i want the corresponding address to come in the info-window. But when i click on the marker, initially the default value of address(As per code Geo-Address Unavailable!) is coming and when i click the second marker it is having the address of the previously clicked marker. I'm attaching the piece of code.

    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条回答
家丑人穷心不美
2楼-- · 2020-02-15 08:53

Geocoding is asynchronous. You have to use the returned value inside the callback from the geocoder.

What is happening:

  1. you send off a request to the geocoder.
  2. you display the response
  3. the response comes back from the geocoder
  4. you send off another request to the geocoder
  5. you display the response to the first request
  6. the response comes back from the geocoder to the second request
查看更多
登录 后发表回答