Javascript Pass Parameter To Callback Or Set Variable Value In Distancematrixstatus
I have been playing a little bit with Google's DistanceMatrixService. The code below works, but, how can I pass another parameter to the callback function or grab one of the values
Solution 1:
You can't change how Google calls the callback, but you can let it call your own locally function as the callback and then have that (via a closure) call another callback after adding the desired extra argument like this:
functionGoogleMapDistance(YourLatLong,DestLatLong, item)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [YourLatLong],
destinations: [DestLatLong],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {callback(response, status, item)});
}
Or, you could just define your callback inline so it has access to the parent function variables directly:
function GoogleMapDistance(YourLatLong,DestLatLong, item)
{
varservice=newgoogle.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [YourLatLong],
destinations: [DestLatLong],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function callback(response, status)
{
// you can access the parent scope arguments like item hereif (status == google.maps.DistanceMatrixStatus.OK)
{
varorigins= response.originAddresses;
vardestinations= response.destinationAddresses;
for (vari=0; i < origins.length; i++)
{
varresults= response.rows[i].elements;
for (varj=0; j < results.length; j++)
{
varelement= results[j];
varfrom= origins[i];
varto= destinations[j];
vardistance= element.distance.text;
varduration= element.duration.text;
varResultStr= distance + " (<i>" + duration + "</i>)";
}
}
document.getElementById("Results1").innerHTML = ResultStr;
}
}
)}
Post a Comment for "Javascript Pass Parameter To Callback Or Set Variable Value In Distancematrixstatus"