2

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 enter image description here

When I start going longer distances the calculations get even worse!

  • Rome, Italy - 0km
  • Mohenjo-daro, Pakistan - 0km
  • Istanbul, Turkey - 250km

enter image description here

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!

Kim T
  • 5,770
  • 1
  • 52
  • 79
  • Might want to try the formulas based on the Haversine (half-verserd-sine) to compute distance between two points. JavaScript code is provided at http://www.movable-type.co.uk/scripts/latlong.html – CodeMonkey Feb 04 '14 at 22:38
  • Yes it seems this distToSegment is wrong in a few places – Kim T Feb 06 '14 at 15:23

1 Answers1

1

This

bearing1 = 360 - (bearing1 + 360 % 360)

looks fishy to me. Do you mean

bearing1 = 360 - (bearing1 + 360) % 360

?

Likewise for bearing2.

% is a multiplicative operator and has higher precedence than +.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161