# How can I calculate the distance between two coordinates (latitude and longitude) in JavaScript?Davide Sconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){const t=document.querySelectorAll("img[data-main-image]");for(let e of t){e.dataset.src&&(e.setAttribute("src",e.dataset.src),e.removeAttribute("data-src")),e.dataset.srcset&&(e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset"));const t=e.parentNode.querySelectorAll("source[data-srcset]");for(let e of t)e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset");e.complete&&(e.style.opacity=1,e.parentNode.parentNode.querySelector("[data-placeholder-image]").style.opacity=0)}}

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:

``````1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
``````
function calculateDistance(lat1, lon1, lat2, lon2) {
const earthRadius = 6371; // Radius of the Earth in kilometers
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);

const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) *
Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);

const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = earthRadius * c;

return distance;
}

function toRadians(degrees) {
return degrees * (Math.PI / 180);
}

// Example usage
const distance = calculateDistance(37.7749, -122.4194, 34.0522, -118.2437);
console.log(distance.toFixed(2) + ' km'); // Output: 559.03 km
``````

In this example, the`calculateDistance` function takes four arguments:`lat1` and`lon1` representing the latitude and longitude of the first point, and`lat2` and`lon2` representing the latitude and longitude of the second point. The Haversine formula requires the input to be in radians, so the`toRadians` function is used to convert the degrees to radians. The formula then computes the differences in latitude and longitude (dLat and`dLon`), 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.