2013-02-10 21 views
0

我正在嘗試創建一個利用Google Javascript V3的地理編碼功能並返回一個具有經度和緯度的數組的函數。出於某種原因,返回數組沒有使用該函數進行填充。謝謝你的幫助!如何使用Google Javascript v3 Geocoder返回經緯度數組?

代碼:

function getCoords(address) { 
    var latLng = []; 
    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     latLng.push(results[0].geometry.location.lat()); 
     latLng.push(results[0].geometry.location.lng()); 
     return latLng; 
     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     }  
    }); 
    } 

    var test_arr;  
    test_arr = getLatLng('New York'); 
    alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here. 
+0

異步API不同步。做回調工作。 – 2013-02-10 03:39:16

回答

0

閱讀關於在Javascript中使用回調函數。 This article可能會有所幫助。

正如Jon指出的那樣,您可以通過將回調函數傳遞給getCoords方法來解決此問題。這是一種等待Google迴應的方式。您定義了一個函數,當地理編碼完成時將會調用該函數。您不用返回數據,而是將數據作爲參數調用提供的函數。

事情是這樣的:

function getCoords(address, callback) { 
    var latLng = []; 
    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     latLng.push(results[0].geometry.location.lat()); 
     latLng.push(results[0].geometry.location.lng()); 
     callback(latLng); 
    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    }  
    }); 
} 

getCoords('New York', function(latLng) { 
    var test_arr; 
    test_arr = latLng; 
    alert(test_arr[0] + ',' + test_arr[1]) 
    // Continue the rest of your program's execution in here 
}); 
0

@馬特球應該已經張貼了答案。 :) test_arr未定義的原因是因爲您在結果回來之前立即對其進行評估。

如果你做了一個setTimeout(你不應該這樣做),你會注意到最終數組會有一些東西在裏面。

setTimeout(function(){ 
    alert(test_arr) // has stuff... 
}, 5000); 

相反,您可以將匿名函數傳遞給getCoords作爲回調函數。一旦座標可用,該函數就會被執行。

function getCoords(address, callback) { 
    ... 
    var lng = results[0].geometry.location.lng(); 
    var lat = results[0].geometry.location.lat(); 
    callback([lat, lng]); 
    ... 
} 

getCoords("New York", function(coords) { 
    alert(coords); // works 
}); 
相關問題