我試圖實現谷歌地圖和我遇到的問題是,當我調用函數getLatLng,它返回一個未定義的值,我不明白爲什麼。JavaScript函數返回undefined
initialize();
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var myLatLng = getLatLng(address);
console.log("myLatLng = "+myLatLng);
}
function getLatLng(address) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
});
console.log("codedAddress 3 = "+codedAddress);
return codedAddress;
}
在Firebug控制檯,這裏是我得到這個確切順序輸出:
codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)
爲什麼codedAddress 3和myLatLng首先顯示在控制檯中了?
不,我實際上有一個關閉括號,但我只是遺漏了一些其他的東西,忘了複製那個括號。 – Catfish 2011-05-25 02:53:12