leichter / cwrx

(Old) Cinema6 API
0 stars 0 forks source link

Update geo svc to do zipcode radius lookups #951

Open leichter opened 8 years ago

leichter commented 8 years ago

Something we originally planned to do but never really needed; I'm putting in this issue to document the kind of complicated mongo query necessary for this.

The zipcodes are saved in the db with a loc param, which is an array like [ <longitude>, <latitude> ]. These can be used with a $near query to get other entities within a radius of the point. Example:

// Mongo shell code, would need to be adapted to use actual mongo node driver
// Finds all zipcodes within 20 miles of princeton
var princeton = db.zipcodes.findOne({ zipcode: '08540' });
var nearPrinceton = db.zipcodes.find({
    "loc" : {
        "$near" : {
            "$geometry" : {
                "type" : "Point",
                "coordinates" : princeton.loc
            },
            // expected units are meters, so convert miles to meters by multiplying by 1609.34
            "$maxDistance" : 20 * 1609.34 
        }
    }
}).toArray();

Unsure how this would be expressed in query params on the API request. Maybe something like GET /api/geo/zipcodes?near=08540&distance=20

If we wanted to get all zipcodes within a radius of several different zipcodes, you should be able to combine this $near operator with the $or operator to construct a proper query.