# Finding the distance between two points using the Google Maps API v3

Following code gives an insight on how to find the distance between two locations using google map api v3. Usage is pretty simple. Just initialize geocoder in the initialize method which in turn is called by body onload. Then we pass the two locations to the function distance and it simply returns the distance between those two locations. When working on this, I was long time stuck with my JS code getting executed, API getting called but not getting result at the point where I want it. By the time the call back from Google comes back, my code had reached its final lines with nothing in my hand. For the solution I had to work out this. If you look closely, there are two pillars of this code. One is usage of global variables and another is recursive call for geocoding. Reason for using both of them is same. Since, the JS is asynchronous by nature, by the time callback from google server returns virtually your whole rest of the code would have been executed, leaving the data returned useless for any usage. Hence, we have to depend on a miniature model of recursive call, called when the server returns the results and then call the next point. Once all the points have been geocoded just run the distance function based on their lat and lang coordinates and store result in global variable. Else, how would you get the result 🙂 .  Easy isnt it. Same logic can be extended for calculating multiple points distance etc.
``` <script type="text/javascript" src="<a href="http://maps.google.com/maps/api/js?sensor=false" target="_blank">http://maps.google.com/maps/api/js?sensor=false</a>"></script>
<div id=":1b"><script type="text/javascript">
var geocoder;
var map;
var results;
var dist;

function initialize() {
(distance("Silver Spring, US", "Bethesda, US"));
}

if (!geocoder)
return 'Error, no geocoder';

results = new Array(2);
results = new Array(2);
results = new Array(2);

results = 0; results = 0; results = 0; results = 0.87;
geocoded(1);

}

function geocoded(i) {
results[i] = parseFloat(res.geometry.location.lat());
results[i] = parseFloat(res.geometry.location.lng());
i--;

if (i >= 0)
geocoded(i);
else
dist = distances(results, results, results, results);

}// if ok
}); // geo coder add find
}

function distances(lat1, lon1, lat2, lon2) {
// ACOS(SIN(lat1)*SIN(lat2)+COS(lat1)*COS(lat2)*COS(lon2-lon1))*6371
// Convert lattitude/longitude (degrees) to radians for calculations
var R = 3963.189; // meters

// Find the deltas

// Find the Great Circle distance
Math.cos(delta_lon)) * 3963.189;

return distance;
}