首页 > 解决方案 > 如何根据位置显示数据

问题描述

我想构建一个用户发布某种文本的应用程序,任何人都可以访问“博客文章”,但我只希望 X KM 半径内的人阅读它(将其显示在该半径内用户的提要上) 什么是最好的方法吗?提前致谢。

尝试将坐标上传到数据库,但不知道如何从那里继续程序检查半径内的位置,然后显示博客文章

标签: phpnode.jsreactjs

解决方案


在 Node.js 中,我建议将 firestore 与geofirex一起使用,这样您就可以在一定范围内进行搜索,并且借助 firebase 功能,您甚至可以创建实时查询。

我制作了这个只显示半径内的点的网络应用程序。

存储和读取值的主要功能如下:

阅读

const DEFAULT_POINT = geo.point(32.520666, -117.021315);
const opinions = db.collection('opinions');

const opinionsSubscribe = () => {
  // Here we check opinions within 22km of radius
  // 'position' is the field where we store our geofirex point
  const query = reports.within(DEFAULT_POINT, 22, 'position');
  // This pipe just parse the data to geojson to make it easy to render directly on a map (tested with google and esri)
  const obs = query.pipe(toGeoJSON('position', true));
  obs.subscribe((geoj) => {
    console.log('reports changed');
    mainReportsData.geo = geoj;
    io.emit('reports', {
      metric: mainReportsData.geo,
    });
  });
};

opinionsSubscribe();

写作


const storeOpinion = (uid, info, res) => {
  const {
    address,
    latitude,
    longitude,
    opinion,
  } = info;
  const lat = parseFloat(latitude);
  const lon = parseFloat(longitude);
  const timestamp = admin.firestore.FieldValue.serverTimestamp();
  // We use default firestore add function, so we need to extract the data from geofirex GeoPoint function
  const { data } = geo.point(lat, lon);
  // The attribute that stores entry location
  const position = {
    geopoint: new admin.firestore.GeoPoint(lat, lon),
    geohash: data.geohash,
  };
  opinions.add({
    address,
    timestamp,
    user: uid,
    position,
  })
    .then(() => {
      res.send({ data: 'success' });
    })
    .catch(() => {
      res.send({ data: 'error' });
    });
};

您可以从这个项目中探索代码,几乎是相同的代码,请随时提出任何问题。


推荐阅读