I am calculating how far away a point is from a line segment on the earth.
My function seemed to work, but as i've increased the distances it's clear it's not working. I presume this is due to the curvature of the earth.
In my calculations Rome is shown as 5km from the line:
- London, UK - 0km
- Rome, Italy - 5km
- Cyrene, Libya - 0km
But on Google Earth it's actually more like 61km
When I start going longer distances the calculations get even worse!
- Rome, Italy - 0km
- Mohenjo-daro, Pakistan - 0km
- Istanbul, Turkey - 250km
I believe the problem is somewhere in the code here:
function distToSegment(lat1, lon1, lat2, lon2, lat3, lon3) {
var y = Math.sin(lon3 - lon1) * Math.cos(lat3);
var x = Math.cos(lat1) * Math.sin(lat3) - Math.sin(lat1) * Math.cos(lat3) * Math.cos(lat3 - lat1);
var bearing1 = radiansToDegrees(Math.atan2(y, x));
bearing1 = 360 - (bearing1 + 360 % 360);
var y2 = Math.sin(lon2 - lon1) * Math.cos(lat2);
var x2 = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lat2 - lat1);
var bearing2 = radiansToDegrees(Math.atan2(y2, x2));
bearing2 = 360 - (bearing2 + 360 % 360);
var lat1Rads = degreesToRadians(lat1);
var lat3Rads = degreesToRadians(lat3);
var dLon = degreesToRadians(lon3 - lon1);
var distanceAC = Math.acos(Math.sin(lat1Rads) * Math.sin(lat3Rads) + Math.cos(lat1Rads) * Math.cos(lat3Rads) * Math.cos(dLon)) * 6371;
var min_distance = Math.abs(Math.asin(Math.sin(distanceAC / 6371) * Math.sin(degreesToRadians(bearing1) - degreesToRadians(bearing2))) * 6371);
return min_distance;
}
Here is a working fiddle you can use to test:
http://jsfiddle.net/kmturley/cfg2D/3/
Any help to figure this one out would be appreciated!