Skip to content

Instantly share code, notes, and snippets.

@chrisjhoughton
Created August 14, 2014 10:56
Show Gist options
  • Save chrisjhoughton/25c390a6e37ce4a418a6 to your computer and use it in GitHub Desktop.
Save chrisjhoughton/25c390a6e37ce4a418a6 to your computer and use it in GitHub Desktop.
SailsJS Geo-encoding and lookup
module.exports.bootstrap = function (cb) {
// Ensure we have 2dsphere index on Property so GeoSpatial queries can work!
sails.models.YOURMODEL.native(function (err, collection) {
collection.ensureIndex({ coordinates: '2dsphere' }, function () {
// It's very important to trigger this callack method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
});
});
};
module.exports = {
attributes: {
coordinates: {
type: 'json'
}
},
/*
* Search models based on location
*/
search: function (conditions) {
// Let's build up a MongoDB query
var query = {};
// We need to use `native` for geo queries
Property.native(function (err, collection) {
// Co-ordinates are passed from the client side (GMaps JS API)
// Note that we don't get them server-side because apparently
// the server-side API isn't designed for real-time user searches.
// Probably too slow or something.
query.coordinates = {
$near: {
$geometry: {
type: "Point",
coordinates: [ // long then lat
conditions.coordinates.lng,
conditions.coordinates.lat
]
},
// $maxDistance : <distance in meters> // TODO
}
};
});
}
}
@PascalAnimateur
Copy link

I've created a gist with a more detailed example and has the maxDistance parameter (expressed in km). Check it out here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment