The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.
in Javascript
const earthRadius = 6378137
const toRad = value => (value * Math.PI) / 180
const robustAcos = value => value > 1 ? 1 : value < -1 ? -1 : value
// Calculates the distance between two points, in meters
// lat(itute) range: -90 to 90; > 0 North, < 0 South of equator
// lon(gitude) range: -180 to 180; < 0 West, > 0 East of Greenwich, UK
export const geoDistance = ( fromLat, fromLon, toLat, toLon, accuracy = 1 ) => {
const distance =
Math.acos(
robustAcos(
Math.sin(toRad(toLat)) * Math.sin(toRad(fromLat)) +
Math.cos(toRad(toLat)) *
Math.cos(toRad(fromLat)) *
Math.cos(toRad(fromLon) - toRad(toLon))
)
) * earthRadius;
return Math.round(distance / accuracy) * accuracy;
};
based on
Library to provide basic geospatial operations like distance calculation, conversion of decimal coordinates to sexagesimal and vice versa, etc. This library is currently 2D, meaning that altitude/elevation is not yet supported by any of its functions!
Weekly Downloads 170K, Last publish 3 months ago, MIT licenseHaversine formula in Javascript. In meters. Nothing more.
MIT, 31K down, updated 3 years ago
both provide same results
No comments:
Post a Comment