我有一系列位置(城市(,我想从当前位置的位置从该位置数组中找到。
我想测试用户位置与我的数组之间的距离,以查看最接近的位置。我该怎么做?
有一个很好的文档,即如何计算两个地理位置之间的距离,并在此处找到JavaScript示例。
计算距离/纬度/经度点之间的距离,轴承以及更多
此页面介绍了纬度/经度的各种计算点,配有用于实施的公式和代码片段。
所有这些公式均用于基于球形的计算地球(忽略椭圆形效果( - 足够准确*大多数目的……[实际上,地球非常椭圆形;使用球形模型的错误通常高达0.3%1 - 请参阅注释更多详细信息]。
假设您有一个与城市的地理位置的数组,则可以通过React-Native的地理位置API进行循环并计算距离的距离。
假设您将数据作为数组/对象的数组。对于演示代码,我正在使用数组。
const cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
["city4", 5, 80, "blah"]
];
deg2Rad = (deg) => {
return deg * Math.PI / 180;
}
pythagorasEquirectangular = (lat1, lon1, lat2, lon2) => {
lat1 = this.deg2Rad(lat1);
lat2 = this.deg2Rad(lat2);
lon1 = this.deg2Rad(lon1);
lon2 = this.deg2Rad(lon2);
const R = 6371;
const x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
const y = (lat2 - lat1);
const d = Math.sqrt(x * x + y * y) * R;
return d;
}
nearestCity = (latitude, longitude) => {
let mindif = 99999;
let closest;
for (index = 0; index < cities.length; ++index) {
const dif = this.pythagorasEquirectangular(latitude, longitude, cities[index][1],
cities[index][2]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
return cities[closest]
}
或类似的东西。另外,您可以使用地理位置获得当前位置。用您当前的LON致电nearestCity(lat, lon)
。希望这会有所帮助。
该方法已经在先前的反应中使用,不幸的是它不适合React天然。我已经编辑了代码,以便它适用于React Native。
代码如下:
cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
["city4", 5, 80, "blah"]
];
nearestPlace = null;
deg2Rad = (deg) => {
return deg * Math.PI / 180;
}
pythagorasEquirectangular = (lat1, lon1, lat2, lon2) => {
lat1 = this.deg2Rad(lat1);
lat2 = this.deg2Rad(lat2);
lon1 = this.deg2Rad(lon1);
lon2 = this.deg2Rad(lon2);
const R = 6371;
const x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
const y = (lat2 - lat1);
const d = Math.sqrt(x * x + y * y) * R;
return d;
}
nearestCity = (latitude, longitude) => {
let mindif = 99999;
let closest;
for (let index = 0; index < this.cities.length; index++) {
const dif = this.pythagorasEquirectangular(latitude, longitude, this.cities[index][1],
this.cities[index][2]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
this.nearestPlace = closest
}
所以当您this.nearestCity (yourLat, yourLon)
时,您会在this.nearestPlace
中找到结果。
您可以使用其他软件包来计算距离,例如https://github.com/cmoncrief/geodist
然后,您可以通过代码在两个点之间计算距离
var geodist = require('geodist')
var dist = geodist({lat: 41.85, lon: -87.65}, {lat: 33.7489, lon: -84.3881})
console.log(dist)
// => 587