0

GetLocation から変数を返そうとしていcoordますが、undefined しか返されません。どんな助けでも大歓迎です!

var coord = "";
function GetLocation(address) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            coord = ParseLocation(results[0].geometry.location);

            // This alert shows the proper coordinates 
            alert(coord);
        }
        else{ }

    });

    // this alert is undefined
    alert(coord);
    return coord;
}

function ParseLocation(location) {

    var lat = location.lat().toString().substr(0, 12);
    var lng = location.lng().toString().substr(0, 12);

    return lat+","+lng;
}
4

1 に答える 1

2

外部関数から戻るときcoords、実際にはまだundefinedです。内部関数は、非同期操作 (非同期でない場合、API は通常どおり結果を返すだけです) が完了したときに後で実行されます。

コールバックを渡してみてください:

function GetLocation(address, cb) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            cb(ParseLocation(results[0].geometry.location));
        }
        else{ }

    });
}

その後、次のように使用できます。

GetLocation( "asd", function(coord){
    alert(coord);
});
于 2012-08-23T19:38:40.403 に答える