问题
I have a set of 10 citys and want to find out which one is the closest to a given longitude/latitude.
Any ideas how to do that using javascript?
thx. rttmax
回答1:
From this site, you can use the Haversine formula:
a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c
Which 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 that for all of the cities using a loop and find the smallest.
来源:https://stackoverflow.com/questions/17594401/find-closest-city-to-given-longitude-latitude