根据用户位置显示某些帖子

Display certain posts based on User Location

本文关键字:显示 用户 位置      更新时间:2023-09-26

我正试图弄清楚如何根据用户的位置显示某些mongoDB帖子。我已经设置了一个搜索功能,让人们搜索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)

}

我希望你用的是猫鼬。请在您的服务器上尝试此代码。我已经使用$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});
          }
        }); 
        }