In this post, I will explain by example how we can find nearest locations by given latitude and longitude with MongoDB.
First step – Create schema:
// create geolocation Schema
const GeoSchema = new Schema({
type: {
type:String,
default:’Point’
},
coordinates: {
type: [Number],
index:’2dsphere’
}
});
// create user Schema & model
const UserSchema = new Schema({
name: {
type:String,
required: [true, ‘Name field is required’]
},
geometry:GeoSchema
});
The users
the collection will store a list of documents, each one of them represents a location(or an address) on the map.
A document in users collection looks like this:
{
_id: OnjectId(“5cfde8a67c100914e8b8d393”)
name: “test”,
geometry: {
coordinates: [ 55.2793 //longitude, 25.1973//latitude ],
type: “Point”,
_id: ObjectId(“5cfa30431ad5133e93a62fda”)
}
}
Second Step – Find query:
const users = await User.aggregate([
{
$geoNear: {
near: {
type:’Point’,
coordinates: [parseFloat(req.query.lng), parseFloat(req.query.lat)]
},
distanceField:’dist.calculated’,
maxDistance:parseFloat(req.query.maxDistance),
spherical:true
}
}
]);
This query will return the nearest users/locations in the range(maxDistance).