没有从地理编码器获得正确的返回值?

时间:2012-02-23 10:53:32

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

我有一系列的位置,使用地理编码器,我能够获得纬度和放大器。经度。但是,我想每次从地理编码器功能中传递位置值。

var locations=new Array("Delhi","Jaipur")
for(var i=0;i<locations.length;i++){
var tempLoc=locations[i];        
geocoder.geocode( { 'address': tempLoc},function(results, status)
{
      if (status == google.maps.GeocoderStatus.OK) {

              latitude[i] = results[0].geometry.location.lat();
              longitude[i] = results[0].geometry.location.lng();          
     latLonArray[i]=new google.maps.LatLng(latitude[i],longitude[i]); 
     latlngbounds.extend( latLonArray[ i ] );
     map.setCenter(latlngbounds.getCenter());
              map.fitBounds(latlngbounds);                     
              createMarker(latLonArray[i],tempLoc);
        }             
});

}

function createMarker(pos,t){
var marker = new google.maps.Marker({       
    position: pos, 
    map: map, 
    title: t      
}); 
google.maps.event.addListener(marker, 'click', function() { 
infowindow.setContent(marker.title);
infowindow.open(map, marker);

}); 
return marker;  
}

位置标记完美,但是当调用点击事件时,信息窗口不会根据位置显示(对于每个标记,信息窗口将标题显示为最后位置[“jaipur”])。

1 个答案:

答案 0 :(得分:0)

原因是地理编码器的响应是异步的。 for循环遍历每个元素,因为'Jaipur'是最后一个值,即当地理编码器的响应最终进入并调用createMarker时仍然存储在tempLoc中的值:

createMarker(latLonArray[i],tempLoc);   
// by this time tempLoc always equals tempLoc=locations[locations.length-1];

您真正想做的是返回地理编码器返回的名称

results[0].address_components[0].long_name

因此,您对createMarker的调用将如下所示:

createMarker(latLonArray[i], results[0].address_components[0].long_name );