我正在尝试让我的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);
});
});
});
答案 0 :(得分:1)
navigator.geolocation就是你想要的。
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
至少在Firefox中,您应该会看到一个弹出窗口,询问您是否允许浏览器发送您的位置。您可能已将其用于使用Google Maps API的网站。