Home > Software design >  Mongoose - Least distance between two co-ordinates (Not GEOJson Data)
Mongoose - Least distance between two co-ordinates (Not GEOJson Data)

Time:02-16

From a list of buildings, the operator will choose one.

and click on it from the front end.

The list of buildings is stored in the MongoDB database and each one has a x,y point demonstrating distance from the 0 origin.

The list is stored in MongoDB database and accessed with node.

Each building has a x,y co-ordinate -- sample only, NOT geojson data

like 101,203 etc.

The Mongoose function will :

  1. Operator clicks on a button and that co-ordinates are used

  2. The funciton will search through the list of buildings and return the nearest one to the one provided --- not the nearest one to the 0 origin.

Any suggestions on how to do with Mongoose?

thanks! Karen

CodePudding user response:

This is really just a math problem. Consider a set of building docs with these x,y coords:

var r =   [
    {_id:1, x:7, y:11}
    ,{_id:2, x:15, y:10}
    ,{_id:3, x:10, y:9}
    ,{_id:4, x:1, y:8}
    ,{_id:5, x:3, y:7}
    ,{_id:6, x:16, y:5}
    ,{_id:7, x:4, y:3}
    ,{_id:8, x:7, y:3}
    ,{_id:9, x:6, y:1}
    ,{_id:10, x:21, y:1}
];

A button is clicked and produces point 6,5:

var P = {x:6, y:5};

To find buildings closest, just iterate and compute distance using pythagorean theorem:

db.foo.aggregate([
    //  Don't have to worry about absolute value of x-x1 thanks to                                         
    //  pow(2) making it positive                                                                          
    //  dist = sqrt((x-x1)^2   (y-y1)^2)                                                                   
    {$addFields: {dist: {$sqrt: {$add:[{$pow:[{$subtract:['$x',P.x]},2]}, {$pow:[{$subtract:['$y',P.y]},2]}]}} }},
    {$sort: {'dist':1}},
    {$limit: 1}
]);

{ "_id" : 8, "x" : 7, "y" : 3, "dist" : 2.23606797749979 }

Remove the $limit or change it to a higher number to see the next closest buidlings.

  • Related