0

Possible Duplicate:
How do I calculate distance between two latitude-longitude points?

How can I calculate the distance in meters between to geo locations in JavaScript? I found this answer but it is implemented in Java, and I did not really understand what was going on.

I am using HTML 5's geo location feature and using JavaScript to calculate the distance. Till now I have this function:

    function calculateDistance(lat1, lat2, lng1, lng2)
    {
        return Math.sqrt(((lat1 + lat2)*(lat1 + lat2)) + ((lng1  + lng2)*(lng1  + lng2)));
    }

Obviously this is not the value I require. Can anybody help me please?

Community
  • 1
  • 1
Goaler444
  • 2,591
  • 6
  • 35
  • 53
  • You have to treat it as a spherical geometry problem. That is, what you have to find is the length of the arc on the surface of a sphere (which isn't really right either but it's closer). – Pointy Jan 23 '13 at 17:10
  • A bit more Googling would show that this [question has been asked before](http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points). And the solution is even in JavaScript! – voithos Jan 23 '13 at 17:11
  • @thanks voithos, voting to close this one down then. – Goaler444 Jan 23 '13 at 17:12

2 Answers2

1
var R = 6371; // Earth radius in km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

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)); 
var d = R * c;

This is not my code. It's taken from: http://www.movable-type.co.uk/scripts/latlong.html Check the link for details.

sica07
  • 4,896
  • 8
  • 35
  • 54
0

Maybe this can be helpful and this answer can be helpful too.

Community
  • 1
  • 1
Jefferson
  • 794
  • 10
  • 24