给定一个带有坐标的json
:
var centerLat = 51.6000;
var centerLng = 12.8000;
var posts = [
{
name: 'PostA',
latitude: '52.5167',
longitude: '13.3833',
},
{
name: 'PostB',
latitude: '52.9667',
longitude: '13.7167',
},
{
name: 'PostC',
latitude: '26.7767',
longitude: '18.4567',
}
];
我在 this link 上找到了 haversine 公式,如何检查是否从 获得了给定的
是否在5公里的lat
和 lng
列表使用半正矢,json半径
内?
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
最佳答案
您可以执行此操作来过滤城市,您提供的数据相距太远,以获取结果中的任何内容,我已经移动了 centerLat
和 centerLng
我有最后记录了最近城市的数组。
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1); // deg2rad below
var dLon = deg2rad(lon2 - lon1);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI / 180)
}
var centerLat = 52.5167;
var centerLng = 13.3933;
var posts = [{
name: 'PostA',
latitude: '52.5167',
longitude: '13.3833',
},
{
name: 'PostB',
latitude: '52.9667',
longitude: '13.7167',
},
{
name: 'PostC',
latitude: '26.7767',
longitude: '18.4567',
}
];
let closePosts = [];
posts.forEach((post) => {
if (getDistanceFromLatLonInKm(centerLat, centerLng, post.latitude, post.longitude) < 5) {
closePosts.push(post);
}
});
console.log(closePosts)
关于javascript - 如何检查坐标是否在以公里为单位的半径范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953691/