Dinosaur Tracks Musuem, Potosi, Bolivia

Using Location in NodeJS and MongoDB

Written by R.D.M.

I’ve been slowly working on a dating app as a side project. Android front end and NodeJs, Express, and Mongodb on the backend. As with most dating apps, it needs to be able to filter the users by location. Here’s how I did it on the backend.


Insert a Document with a Lat/Long field

Create a document with a Lat/Long field, ‘pos’ here, that has an array with two doubles as the value (longitude THEN latitude).

self.db.collection('users').insert( {'pos' : [lon,lat], 'id' : id } );


Apply Geospacial index

This code applies a geospatial index to the ‘pos’ field.

self.db.collection('users').ensureIndex( { pos : "2dsphere" } );


Write get Nearest Users API call

Do a find query and use the $near, $geometry, and $maxDistance operators to get the nearest users at a position. The API call here is just taking a Lat/Long position and a max distance (in meters) to build a circle around the point. It returns all documents (users in our case) within that circle.

 1 //returns all the users near a distance 
 2 self.routes['returnNearestUsers'] = function(req, res) {
 3     var lat = parseFloat(req.query.lat);
 4     var lon = parseFloat(req.query.lon);
 5     var distance = parseInt(req.query.distance);
 6 
 7     self.db.collection('users').find( { 'pos' : 
 8                                             { $near : 
 9                                               { $geometry :
10                                                 { type : "Point" ,
11                                                   coordinates : [ lon, lat] 
12                                                 },
13                                                 $maxDistance : distance
14                                               }
15                                             }
16                                           }
17         ).toArray(function(err, names) {
18         	res.header("Content-Type:","application/json");
19         	res.end(JSON.stringify(names));
20     });
21 };


Calling RESTful endpoint

API call would look something like this:

http://......api/nearestUsers?lat=89.9034&lon=32.6556&distance=50000

Done At: Oct 19,2015
Categories: