2

Ok guys, I know this topic has already been discussed multiple times, but I can't find an answer to solve my problem.

So I'm trying to do a simple think : I'm creating a string, like : distance is : " + CalculateDistance(position); The wanted result is something like distance is 5kms (8min).

CalculateDistance(position) is a function calling a Google maps API called DistanceMatrix to calculate distance between two points. The API is documented here, and the given sample perfectly works. I adapted it like this :

function CalculateDistance(position)
{
    var service = new google.maps.DistanceMatrixService();
    var destination = new google.maps.LatLng(/* some lat/lng */);

    service.getDistanceMatrix(
    {
        origins: [position],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, callback);
}

function callback(response, status) {
    if (status == google.maps.DistanceMatrixStatus.OK)
    {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        var results = response.rows[0].elements;
        distanceMatrixResult = results[0].distance.text + " ( " + results[0].duration.text + " min)";
    }

Oh, by the way, distanceMatrixResult is a global variable. In fact, I just need to get the content of results[0].distance.text (and when I print it in the console in callback(), the value is OK) and then concatenate the value with "Distance is". If someone have a smarter solution, it is welcomed !

The API call is asynchronous, and in my case, distanceMatrixResult is always empty in the result string. But when I log its value in the console, distanceMatrixResult value became the good one AFTER the string was created.

All I want to write is :

• Call CalculateDistance (which call callback asynchronously)
• When callback is ended, concatenate the string with the distanceMatrixResult value.

I tried some Deferred, like $.done() and $.when().then() but I can't success...

Can someone help me ?
Thank you !

4

1 回答 1

8

distanceMatrixResult是一个全局变量

它不应该,它应该是你的 Promise (Deferred) 所代表的值。这是基本设置:

function calculateDistance(position) {
    var service = new google.maps.DistanceMatrixService();
    var destination = new google.maps.LatLng(/* some lat/lng */);
    var dfd = $.Deferred();
    service.getDistanceMatrix({
        origins: [position],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, function(response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK)
            dfd.resolve(response);
        else
            dfd.reject(status);
    });
    return dfd.promise();
}

现在,你想做

calculateDistance(…).then(function(response) {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var results = response.rows[0].elements;
    return results[0].distance.text + " ( " + results[0].duration.text + " min)";
}).done(function(distanceMatrixResult) {
    var myString = "distance is: "+distanceMatrixResult;
    // do something with your string now
});
于 2013-10-01T21:16:37.890 回答