Skip to content

Instantly share code, notes, and snippets.

@jameswyse
Created June 22, 2012 12:45
Show Gist options
  • Save jameswyse/2972551 to your computer and use it in GitHub Desktop.
Save jameswyse/2972551 to your computer and use it in GitHub Desktop.
Find postcodes within range of another postcode. Tags: NodeJS, MongoDB, Mongoose, RailwayJS, ExpressJS
// http://localhost:4000/api/postcodesNear?postcode=4101&range=2
action('postcodesNear', function () {
var earthRadius = 6378;
var qPostcode = req.query.postcode || 4101;
var qRange = Number(req.query.range) || 2;
Postcode .findOne({ 'postcode': qPostcode })
.run(function(err, postcode) {
if (err) send(err);
else {
nearby = postcode.near(qRange, function(err,postcodes) {
if(err) send(err);
else {
postcodes.documents[0].results.forEach(function(location){
location.dis = location.dis * earthRadius;
});
send(postcodes.documents[0].results);
}
});
}
});
});
var PostcodeSchema = new Schema({
postcode: { type: String, required: true, index: true },
locality: { type: String, required: true },
state: { type: String, required: true, enum: ['ACT', 'NSW', 'VIC', 'QLD', 'SA', 'WA', 'TAS', 'NT'] },
loc: [],
lat: { type: String },
lon: { type: String }
});
//PostcodeSchema.index({ 'loc': '2d'});
PostcodeSchema.methods.near = function findNearby (qRange, callback) {
var earthRadius = 6378;
var range = Number(qRange) || 2;
return this.db.db.executeDbCommand({
geoNear : "postcodes",
near: this.loc,
spherical: true,
maxDistance : range / earthRadius,
includeLocs : true
}, callback);
};
var Postcode = mongoose.model('Postcode', PostcodeSchema);
Postcode.modelName = 'Postcode';
module.exports['Postcode'] = Postcode;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment