问题
I want to know if I get a lat-long of a user and want to check if he lies in any of the polygon that is stored in my db (MongoDB). How can this be achieved using mongoDB. For instance my db will have 10 polygons stored as GeoJson objects. I get a lat-long and want to check if this lat-long lies in any of the 10 polygons in my DB. Can this be achieved in MongoDB?
回答1:
I dont think your particular case can be achieved in MongoDB. MongoDB does have polygon calculations with the $polygon operator. However, this operator takes a polygon and confirms if any documents are within it not the other way round.
回答2:
I wrote this code in javascript it is working fine for me
var polygonData = "43.64486433588385,-79.3791389465332;43.64508171979899,-79.3930435180664;43.63682057801007,-79.38437461853027;43.63946054004705,-79.36819553375244;43.652720712083266,-79.37201499938965;43.65793702655821,-79.39111232757568;43.64927396999741,-79.37222957611084";
var lat='43.64927396999741'; var lng='-79.37222957611084';
polySearch(polygonData,lat,lng);
function polySearch(polygonData,lat,lng){ var lat_long=lat+","+lng;
var longitude_x = lng;
var latitude_y = lat;
var is_in_polygon=false;
var vertices_x=[];
var vertices_y=[];
var arr=polygonData.split(';');
for(var j=0; j<arr.length; j++){
var arr1=arr[j].split(',');
vertices_x.push(arr1[1]);
vertices_y.push(arr1[0]);
}
var points_polygon = vertices_x.length;
var isIn=isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y);
if (isIn==1)
console.log('Which is in polygon');
else
console.log('Which is not in polygon');
function isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y)
{
var i = 0;
var j = 0;
var c = 0;
for (i = 0, j = points_polygon-1 ; i < points_polygon; j = i++) {
var val="((("+vertices_y[i]+" > "+latitude_y+") != ("+vertices_y[j]+" > "+latitude_y+")) && ("+longitude_x+" < ("+vertices_x[j]+" - "+vertices_x[i]+") * ("+latitude_y+" - "+vertices_y[i]+") / ("+vertices_y[j]+" - "+vertices_y[i]+") + "+vertices_x[i]+"))";
if(eval(val))c=!c;
}
return c;
}
}
回答3:
Sorry to only past two links, but i think these explains what should be done far better then i would:
A SO answer in the same subject
An excellent tutorial how to use mongodb geospatial indexes
来源:https://stackoverflow.com/questions/17355519/find-if-given-lat-long-lies-in-any-of-the-polygon-in-mongodb