查找距离给定经度/纬度的最近城市 [英] Find closest city to given longitude/latitude

查看:126
本文介绍了查找距离给定经度/纬度的最近城市的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一套10个城市,想找出哪一个最接近给定的经度/纬度。

任何想法如何使用javascript?



thx。 rttmax

解决方案

From

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

可以用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;

然后,对于所有使用循环的城市执行此操作,并找到最小值。


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

解决方案

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.

这篇关于查找距离给定经度/纬度的最近城市的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆