I am using the Haversine formula to calculate the distance from two latitude-longitude pairs.
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var lat1 = deg2rad(lat1);
var lat2 = deg2rad(lat2);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) *
Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Given a starting point (lat1, lat2), the distance required to move on a straight line and the angle, I need to determine the endpoint (as in lat2 and lon2).
See my attempt below:
function getFinalLatLon(lat1, lon1, distance, angle) {
var R = 6371; // Radius of the earth in km
var c = distance/R;
// Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) = c/2
var a = // stuck here
// looking for this part of the code
return [lat2, lon2];
}
If you are moving horizontally, you can increment the longitude by
distance / (R * cos(lat)). Noatanneeded.EDIT: Since you wanted a formula for the general case, consider the following geometric derivation:
Front view:
Side view:
Entire setup:
Notes:
ris the unit vector of your starting position, andsis the endpoint.a, b, care intermediate vectors to aid calculation.(θ, φ)are the (lat, long) coordinates.γis the bearing of the direction you are going to travel in.δis the angle travelled through (distance / radiusR = 6400000m).We need
a, bto be perpendicular torand alsoaaligned with North. This gives:cis given by (simple trigonometry):And thus we get
s(through some very tedious algebra):Now we can calculate the final (lat, long) coordinates of
susing:Code:
Test cases:
Input
(lat, long) = (45, 0),angle = 0,distance = radius * deg2rad(90)=>(45, 180)(as I said before)Input
(lat, long) = (0, 0),angle = 90,distance = radius * deg2rad(90)=>(0, 90)(as expected - start at equator, travel east by 90 longitude)Input
(lat, long) = (54, 29),angle = 36,distance = radius * deg2rad(360)=>(54, 29)(as expected - start at any random position and go full-circle in any direction)Interesting case: input
(lat, long) = (30, 0), everything else same. =>(0, 90)(we expected(30, 90)? - not starting at equator, travel by 90 degrees to North)The reason for this is that 90 degrees to North is not East (if you're not at the equator)! This diagram should show why:
As you can see, the path of movement at 90 degrees to the North is not in the direction of East.