fxnGetNearestDealer: function () {
//Gets LatLng for given Zipecode and displays the dealer.
fxnGetLatLngforZip(function () {
//Gets The Nearest Dealers Index out of dealers in the site.
fxnGetNearDealerIndex(function (distance) {
alert(distance);
//Gets Html To Display NearestDealer Details.
sHtml = fxnGetHtmlforNearestDealer();
//Displays Nearest Dealer Details in the span with Id "spanDNAddr".
document.getElementById('spanDNAddr').innerHTML = sHtml;
});
});
};
fxnGetLatLngforZip = function (callback) {
var oGeocoder = new google.maps.Geocoder(),
iZipcode = document.getElementById('txtZipCode').value;
//Boundary checks
if (!iZipcode) { return; }
oGeocoder.geocode({ 'address': iZipcode }, function (result, status) {
if (status == google.maps.GeocoderStatus.OK) {
g_oLatLng = result[0].geometry.location;
callback();
}
else {
//Can use status its self to display the error message.
document.getElementById('spanDNAddr').innerHTML = "No Results Found Enter Valid ZipCode";
}
});
};
fxnGetNearDealerIndex = function (callback) {
//Boundary Checks
if (!g_oLatLng) { return; }
var oDealerLatlng = null,
dDistance = null,
tempindex = null,
dTemp = null;
for (var iAddrIdx = 0; iAddrIdx < g_oAddrs.length; iAddrIdx++) {
oRequest = {
origin: g_oLatLng,
destination: new google.maps.LatLng(g_oAddrs[iAddrIdx].latitude, g_oAddrs[iAddrIdx].longitude),
travelMode: google.maps.TravelMode.DRIVING
};
g_oDirections.route(oRequest, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
dDistance = response.routes[0].legs[0].distance.value;
if (!dTemp) {
dTemp = dDistance;
}
else if (dDistance < dTemp) {
dTemp = dDistance;
g_iNearIndex = iAddrIdx;
}
}
});
}
callback(dTemp);
};
in the above function "fxnGetNearestDealer" is the starting point from there i am trying to get latlng for given zipcode as it will be a asynchronous call i had used callback its worked fine..after i have to make another asynchronous call to calculate drivingdistance between given zipcode latlng and each latlng iterated in the forloop..and obtain the least value.i ended up writing like above....the problem it never return any value it gives null in alert. if i see in firebug it iterates all the times request created well, but it never goes into "g_oDirections.route" function , as it is asynchronous i used callback but it didn't work ....any work around plz......
The example below is generic. It shows how to get distaces from one point in Manhattan to multiple zip codes.