I am calculating the distance between two cities in kilometers using their latitude and longitude. According to the Google map, the distance is 33 km
but the number I am getting is 1038 km
.
I understand Google gives the actual distance whereas the haversine formula used in my code tells the distance as the crow flies.
Can someone please help me understand why there is such a huge difference between both numbers?
let cities = [ { city: "St Paul", lat: 44.9537, lon: 93.09 }, { city: "Stillwater", lat: 36.1156, lon: 97.0584 }, ]; function distance(lat1, lon1, lat2, lon2) { var p = 0.017453292519943295; var c = Math.cos; var a = 0.5 - c((lat2 - lat1) * p) / 2 + (c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p))) / 2; return 12742 * Math.asin(Math.sqrt(a)); } let d = distance(cities[0].lat, cities[0].lon, cities[1].lat, cities[1].lon); document.write(d.toFixed(1) + " km");
Advertisement
Answer
I’ve verified the 1038km from another site https://www.movable-type.co.uk/scripts/latlong.html
You can also roughly see the distance by the scale marker (and it’s roughly 1000km).
Your 33km is wrong, or you’ve got the wrong long/lat from somewhere (another town of the same name?).