Javascript函数返回undefined而不是数字

Jon*_*Hwa 0 javascript

我有两个Javascript函数,试图使用Google Maps API Geocode查找地址的纬度和经度:

function getLatLon(address) {
    var location = -1;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat();
            var lon = results[0].geometry.location.lng();
            location = new Array(lat, lon);
            //document.getElementById('results').innerHTML = location[0];
        } else {
            alert("Geocode was not successful.");
        }
    });
    return location;
}

function search() {
    var address = document.getElementById('address').value;
    var location = getLatLon(address);
    document.getElementById('results').innerHTML = location[0];
}
Run Code Online (Sandbox Code Playgroud)

虽然getLatLon()中的location [0]在#results div中打印出正确的数字,但search()中的location [0]返回undefined.你有什么想法可能会发生这种情况吗?我试过从getLatLon()返回一个普通的字符串("Hello"),而且工作得很好.

Mik*_*nty 6

问题geocoder.geocode(...)是异步的,所以你不能返回一个值.试试这样:

function getLatLon(address, callback) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat();
            var lon = results[0].geometry.location.lng();
            location = new Array(lat, lon);
            callback(location);
        } else {
            alert("Geocode was not successful.");
        }
    });
}

function search() {
    var address = document.getElementById('address').value;
    getLatLon(address, function(location) {
        document.getElementById('results').innerHTML = location[0];
    });
}
Run Code Online (Sandbox Code Playgroud)