gpt4 book ai didi

javascript - 如何使用我的位置通过纬度和经度计算两点之间的距离

转载 作者:行者123 更新时间:2023-12-03 05:52:17 24 4
gpt4 key购买 nike

我正在尝试让我的 REST API 只向我发送回特定半径内的项目。我已经编写了代码来计算两点之间的距离,并且只向我发送所需半径内的距离。然而,到目前为止,我使用任意纬度和经度作为比较点。如何在该算法中使用我自己的位置?

app.get('/posts', function(req, res) { 

// Get 'posts' collection from db
db.collection('posts', function(err, collection) {

// Get all documents in the 'posts' collection
collection.find().toArray(function(err, items) {

// Documents to send back
var results = []

//Function that calculates distance between two points.
function calculateDistance (lat1, lat2, lon1, lon2) {
var dLat = deg2rad(lat2-lat1);
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 = (6371 * c); // Distance in km
var e = (d/1.6) //Convert distance in km to miles.
return e
}

// Iterate over each document and check if the distance is correct
for (var i = 0; i < items.length; i++) {
var item = items[i]
if ((calculateDistance(item.latitude, 43.7035798, item.longitude, -72.2887838) > 25)) {
results.push(item)
}

}
res.send(results);
});
});
});

最佳答案

navigator.geolocation 就是你想要的。

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

至少在 Firefox 中,您应该会看到一个弹出窗口,询问您是否允许浏览器发送您的位置。您可能已经为使用 Google Maps API 的网站获取了它们。

关于javascript - 如何使用我的位置通过纬度和经度计算两点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com