Distance between 2 points

This Page is locked
Modified: 2007/09/03 04:45 by ViaVE Visitor
Distance between 2 points

Returns the distance between two points (lat/long) in miles or kilometers.

Params:

point1 = new VELatLong(x, y);
point1 = new VELatLong(x2, y2);
miles = boolean (true returns distance in miles, false returns distance in kilometers)

Usage:
map = new VEMap('myMap');
map.LoadMap();
getDistance(new VELatLong(0,0), new VELatLong(100, 100), true);


Refactored Code:


// Calculate distance between two points specified by latitude/longitude using law of cosines. // ref: http://www.movable-type.co.uk/scripts/LatLong.html function getDistance(p1, p2, miles) { p1.Latitude= latLonToRadians(p1.Latitude); p1.Longitude= latLonToRadians(p1.Longitude); p2.Latitude= latLonToRadians(p2.Latitude); p2.Longitude= latLonToRadians(p2.Longitude);

var R = 6371; // earth's mean radius in km var dLat = p2.Latitude- p1.Latitude; var dLong = p2.Longitude- p1.Longitude; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1.Latitude) * Math.cos(p2.Latitude) * Math.sin(dLong/2) * Math.sin(dLong/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var disKm = R * c; var disMiles = disKm * 0.6214;

return (miles ? disMiles : disKm); }

// convert lat/long in degrees to radians function latLonToRadians( point ) { return point * Math.PI / 180; }



Orginal Code:


// Calculate distance between two points specified by latitude/longitude using law of cosines. // ref: http://www.movable-type.co.uk/scripts/LatLong.html function getDistance( point1, point2, miles) { var p1 = getCoord(point1); p1.lat = latLonToRadians(p1.lat); p1.lon = latLonToRadians(p1.lon); var p2 = getCoord(point2); p2.lat = latLonToRadians(p2.lat); p2.lon = latLonToRadians(p2.lon);

var R = 6371; // earth's mean radius in km var dLat = p2.lat - p1.lat; var dLong = p2.lon - p1.lon; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1.lat) * Math.cos(p2.lat) * Math.sin(dLong/2) * Math.sin(dLong/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var disKm = R * c; var disMiles = disKm * 0.6214;

return (miles ? disMiles : disKm); }

// converts a VE point str to an object function getCoord( point ) { var p = new Object(); point = point.toString(); p.lat = point.split(",")0; p.lon = point.split(",")1; return p; }

// convert lat/long in degrees to radians function latLonToRadians( point ) { return point * Math.PI / 180; }



JonnyAJAX