Find the closest city to a given longitude / latitude

I have a set of 10 cities and want to know which one is closest to the given longitude / latitude.

Any ideas how to do this with javascript?

THX rttmax

+4
source share
1 answer

From this site you can use the Haversin formula:

a = sin²(Δφ/2) + cos1).cos2).sin²(Δλ/2) c = 2.atan2(√a, √(1−a)) d = Rc 

What can be implemented in Javascript:

 var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); var lat1 = lat1.toRad(); var lat2 = lat2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; 

Then just do it for all cities using the loop and finding the smallest.

+4
source

Source: https://habr.com/ru/post/1490902/


All Articles