2012-02-23 8 views
0

私は場所の配列を持っていて、ジオコーダーを使って、私は緯度&経度を得ることができました。しかし、ジオコーダー関数のたびに位置値を渡したいと思います。ジオコーダから正しい戻り値が得られませんか?

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; 
} 

場所は完全にマーキングされますが、クリックイベントが呼び出されたときに情報ウィンドウには、(すべてのマーカーの情報ウィンドウが最後の場所[「ジャイプール」]などのタイトルを示して)場所に応じて表示されていません。

答えて

0

ジオコーダからの応答が非同期であるためです。 forループは、各要素を通過し、「ジャイプール」は最後の値であるから、それはジオコーダからの応答が最終的に来て、createMarkerを呼び出したときに、まだテンプロックに格納された値である:

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

あなたが実際にしたいのか

createMarker(latLonArray[i], results[0].address_components[0].long_name); 
:そのジオコーダは

results[0].address_components[0].long_name 

を返されないバック名を取得するので、createMarkerへの通話は、次のようになります

関連する問題