我正在尝试根据用户的位置弄清楚如何显示某些mongoDB帖子。我已经设置了一个搜索功能,可以让人们搜索MongoDB帖子。我也想出了如何获得用户的位置并找到他们附近的大城市。
假设你在华盛顿特区。我想只在标题中包含华盛顿特区的帖子显示在“显示”页面上。我一直无法解决这个问题。
有什么建议吗?
谢谢!
router.get("/", function(req, res){
if (req.query.search) {
const regex = new RegExp(req.query.search, 'i');
Deals.find({ "name": regex }, function(err, founddeals) {
if(err){
console.log(err);
} else {
res.render("deals/index",{deals:founddeals});
}
});
}
这也会返回离用户最近的城市
// Get User's Coordinate from their Browser
window.onload = function() {
// HTML5/W3C Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(UserLocation);
}
// Default to Washington, DC
else
NearestCity(38.8951, -77.0367);
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
NearestCity(position.coords.latitude, position.coords.longitude);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var lat = 20; // user's latitude
var lon = 40; // user's longitude
var cities = [
["ATL", 33.740231, -84.394521],
["NYC", 40.748163, -73.985946],
["Vegas", 34.825425, -82.545665]
];
function NearestCity(latitude, longitude) {
var mindif = 99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
// echo the nearest city
alert(cities[closest]);
console.log(closest)
}
答案 0 :(得分:-1)
我希望你使用猫鼬。请在您的服务器中尝试此代码。我使用了$ regex并对您的代码进行了一些小修改。
router.get("/", function(req, res){
if (req.query.search) {
Deals.find({ "name":{ $regex: req.query.search } }, function(err, founddeals) {
if(err){
console.log(err);
} else {
res.render("deals/index",{deals:founddeals});
}
});
}