Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

algorithm - Determine compass direction from one lat/lon to the other

Does anyone have an algorithm to determine the direction from one lat/lon to another (pseudo-code):

CalculateHeading( lat1, lon1, lat2, long2 ) returns string heading

Where heading is e.g. NW, SW, E, etc.

Basically, I have two points on a map and I want to get a general idea of the direction taking into account that 50 miles East and one mile North is simply East and not Northeast.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This site has the basic algorithm:

// in javascript, not hard to translate...
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) -
        Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
var brng = Math.atan2(y, x).toDeg();

UPDATED: See here for complete algorith Mapping Math and Javascript

That'll give you a number between 0 and 360 then it's just a matter of having a simple lookup:

var bearings = ["NE", "E", "SE", "S", "SW", "W", "NW", "N"];

var index = brng - 22.5;
if (index < 0)
    index += 360;
index = parseInt(index / 45);

return(bearings[index]);

It's important to note that your bearing actually changes as you move around the earth. The algorithm above shows you initial bearing, but if you're traveling a long distance, your bearing to be significantly different when you reach the destination (if you're only traveling a short distance [< a few hundred kms] then it probably won't change enough to be a concern).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...