0

I want to retrieve from my mongoDb every point inside a certain distance range. Each element stores its position this way : [latitude, longitude] where latitude and longitude are float value.

Ex : I want every point from my db at max 100km from [48.862586, 2.352210]

Calculate the distance between my reference point and all the other to know if the its under the limit distance doesn't sound like a good idea... Is there a way to ask google map API or another one (or by myself) to do that ?

tufekoi
  • 929
  • 2
  • 14
  • 33

2 Answers2

1

Thanks to @AllanNienhuis, he puts me on a good lead. My solution with Node.js + Mongoose :

In Event.js :

var mongoose = require('mongoose');
var EventSchema = new mongoose.Schema({
    name: String,
    pos : [Number],
    type: String
});
EventSchema.index({ pos : '2dsphere' });
module.exports = mongoose.model('Event', EventSchema);

In eventController.js

exports.near = function(req, res) {
    var point = JSON.parse(req.body.point);
    var max = parseInt(req.body.max);
    console.log(point);

    Event.geoNear(point.pos, { spherical : true, maxDistance : max }, function (err, results, stats) {
        if (err) res.json(JsonResponse.get(Code.generic_error, {error: err}));
        else res.json(JsonResponse.get(Code.valid, results ));
    });
};

Works like a charm !

tufekoi
  • 929
  • 2
  • 14
  • 33
0

I would tag this as a mongodb question.

Mongodb supports geospatial functions: http://blog.mongolab.com/2014/08/a-primer-on-geospatial-data-and-mongodb/

Depending on the version of mongo you're using, it could be as simple as:

db.places.find( { loc : 
                  { $near : [ 100 , 100 ],
                    $maxDistance: 10 }
                } )

The newer geoJSON features look really awesome - haven't had time to play with it myself but it looks super flexible. I love being able to find elements within an arbitrary polygon, handled by the DB layer. :)

Allan Nienhuis
  • 3,961
  • 2
  • 23
  • 19
  • If you really wanted, to google maps API does support a method to find a point within a polygon or circle: http://stackoverflow.com/questions/14598426/how-to-detect-if-a-point-is-in-a-circle, but that would be crazy expensive to process. – Allan Nienhuis Apr 02 '15 at 16:09
  • remember that you can only use the geospatial queries on collections with [2d geospatial indexes](http://docs.mongodb.org/v2.2/core/geospatial-indexes/) – jdegens Apr 02 '15 at 16:10
  • thanks, @jdegens - it wasn't obvious from the tutorial linked that they were required. I assumed it was something that you'd obviously want to do, but didn't realize they wouldn't work without indexes. – Allan Nienhuis Apr 02 '15 at 16:14
  • I should have say that I use mongoose with my mongodb (I changed the tag). Thanks @AllanNienhuis for the link, I read in it about geoJson, apparently mongoose officially support it since version 3.8 – tufekoi Apr 03 '15 at 07:54