Click to search on your search term.
Subscribe to Fig Leaf Tutorials

Need help with a project? Contact us at
From code reviews to project "jumpstarts" and full life-cycle development, we've got you covered!
Check out our case studies!
Follow us on Twitter!
Click here to join our Facebook group!

Ready to upgrade your skills? Try these instructor-led classes in Washington, DC:

Calculating the Distance Between Two Points

Page of 168

You can calculate the distance between two points by using either the Haversine formula or the Spherical Law of Cosines. The following function reprsents a JavaScript implementation of the Haversine forumla:

var calcDistance = function(lat1,lng1,lat2,lng2) {

 var R = 3959; // use 3959 for miles or 6371 for km
 var dLat = (lat2-lat1) * Math.PI / 180 ;
 var dLon = (lng2-lng1)* Math.PI / 180;
 var lat1 = lat1 * Math.PI / 180;
 var lat2 = lat2 * Math.PI / 180;

 var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

 return R * c; 

Math is hard. See the Movable Type website for more detail regarding the mathematics of calulating distance from lat/lon.

Page of 168
comments powered by Disqus