How can I calculate the distance between two coordinates (latitude and longitude) in JavaScript?
Davide S
To calculate the distance between two coordinates specified by latitude and longitude in JavaScript, you can use the Haversine formula. The Haversine formula calculates the great-circle distance between two points on the surface of a sphere (in this case, the Earth) given their latitudes and longitudes. Here's an example implementation:
In this example, thecalculateDistance function takes four arguments:lat1 andlon1 representing the latitude and longitude of the first point, andlat2 andlon2 representing the latitude and longitude of the second point.
The Haversine formula requires the input to be in radians, so thetoRadians function is used to convert the degrees to radians.
The formula then computes the differences in latitude and longitude (dLat anddLon), applies the Haversine formula, and calculates the great-circle distance (distance) in kilometers.
Please note that this calculation assumes a perfect spherical Earth, which is a simplification. In practice, the Earth is an oblate spheroid, so for very long distances or high precision, more complex models may be necessary. Additionally, be aware that this calculation does not account for factors like altitude, which may affect the actual distance between two points.