Find closest city to given longitude/latitude [closed]

瘦欲@ 提交于 2019-12-03 15:03:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!