Filter locations in an area of X km

13

I'm trying to build a small project where I have a list of places and I can filter them according to a quantity x of km. Ex: Filter all places within a 5km radius of my current location.

I have Json with some places in my city and when I try to make a 2km filter the Json returns blank, but if I pass 50km as a parameter all data is returned. I can not figure out where I'm going wrong.

Here's some code snippet:

var mongoose = require('mongoose');
var Location = mongoose.model('Location');

// create an export function to encapsulate the controller's methods
module.exports = {
  index: function(req, res, next) {
    res.json(200, {
      status: 'Location API is running.',
    });
  },
  findLocation: function(req, res, next) {
    var limit = req.query.limit || 10;

    // get the max distance or set it to 8 kilometers
    var maxDistance = req.query.distance || 8;

    // we need to convert the distance to radians
    // the raduis of Earth is approximately 6371 kilometers
    maxDistance /= 6371;

    // get coordinates [ <longitude> , <latitude> ]
    var coords = [];
    coords[0] = req.query.longitude || 0;
    coords[1] = req.query.latitude || 0;

    // find a location
    Location.find({
      loc: {
        $near: coords,
        $maxDistance: maxDistance
      }
    }).limit(limit).exec(function(err, locations) {
      if (err) {
        return res.json(500, err);
      }
      res.json(200, locations);
    });
  }
};

This is the Json I'm using:

[
  {
    "name": "Igreja Matriz",
    "loc": [
      -49.974762,
      -23.160631

    ]
  },
  {
    "name": "Prefeitura Jacarezinho",
    "loc": [
      -49.973597,
      -23.159745
    ]
  },
  {
    "name": "Lotérica",
    "loc": [
      -49.980461,
      -23.164231
    ]
  }
]

I pass the parameters by QueryString as follows: http://localhost:3000/api/locations?longitude=-49.978440&latitude=-23.169557&distance=2

Console and result:

How do I get the desired result?

    
asked by anonymous 21.04.2016 / 14:50

1 answer

5

The error in question is acceptable in view of the work scale and the reference system used. An alternative to increase radius accuracy, if your study area fits into a spindle, would be to use the UTM projection system. That way the radius will be reported in meters.

You can also use a geographic database, such as PostgreSQL / PostGIS, which solves this type of situation easily. Your query would work as follows:

-- para um raio de 50 km = 50.000 m:
SELECT ST_Buffer(geom::geography,50000) AS geom
FROM nome_tabela
WHERE condicao;

I'll give you some links on the subject:

PostGIS - Geometry or Geography find points within distance in meters

PostGIS: extraction of measures in tables with geographic coordinates

PostGIS - When to use Geography Data type over Geometry data type

I hope I have collaborated:)

    
27.04.2016 / 23:18