distanceMatrixResult
is a global variable
It should not, it should be the value which your Promise (Deferred) stands for. This is the basic setup:
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();
}
Now, you want to do
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
});