Reputation: 1477
Developing a Javascript application, I am looking for a way to calculate the GPS coordinates of a target point, coming from another position (latitude|longitude) + a certain distance (e. g. 20km further south). To express this as a spoken question one could say: what are the GPS coordinates of my current position plus 20 km to the north|south?
Pseudo formula:
TargetPosition = KnownPosition + Distance
where:
Any ideas for the fomula?
Upvotes: 1
Views: 1459
Reputation: 30725
Once we know the meridional distance in km, and knowing this is 360° of latitude, we can calculate the offset due to moving north or south by x kilometres.
For every degree we move north or south we move (40007.86 / 360) = 111.13 km.
Also we'll include some error checking for locations near the poles..
And I'll add a more general formula for getting a new location given an offset north and east. (Negative for south and west as is the usual convention), this will only be accurate for small displacements.
function getNewLatitude(latitude, distanceKm) {
const meridionalRadiuskm = 40007.86;
latitude = (latitude + distanceKm / (meridionalRadiuskm / 360));
if (latitude > 90) return 180 - latitude;
if (latitude < -90) return -(180 + latitude);
return latitude;
}
console.log(getNewLatitude(50, 100));
console.log(getNewLatitude(50, -100));
// This function may also be useful, you can use this to get a new location base on a north/south / east/west offset in km. Note that accuracy will start to reduce as the offset increases.
function getNewLocation(lat, lon, offsetNorthKm, offsetEastKm) {
// The approximate distance in kilometres of one degree at 0,0.
const ONE_DEGREE_KM = 111.32;
const deltaLatitude = offsetNorthKm / ONE_DEGREE_KM;
const deltaLongitude = offsetEastKm / (ONE_DEGREE_KM * Math.cos(Math.PI * lat / 180));
let result = {
lat: lat + deltaLatitude,
lon: lon + deltaLongitude
}
return result;
}
Upvotes: 2
Reputation: 8134
You can use the Geolib library and it will give you more precise results especially near the poles.
Example: This will compute 15000 meters bearing 180 degress (south) from the provided lat/long.
geolib.computeDestinationPoint(
{ latitude: 52.518611, longitude: 13.408056 },
15000,
180
);
Note that the direction is given in degrees (0 = 360 = north, 180 = south, etc). Using this library will also allow you do other interesting computations like:
Upvotes: 1