Distance from long lat line segment wrong over long distances [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 00:40:42

问题


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!


回答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 +.



来源:https://stackoverflow.com/questions/21563254/distance-from-long-lat-line-segment-wrong-over-long-distances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!