Reputation: 503
I'm trying to find if a geometric point is within one of several polygons, i'm working wiht mongoose and node js. I found in Mongoose documentation this code.
var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
// or
var polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
// or
var polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
// or
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
But all of them are for search in one polygone, i want to search in for example 10 polygons. Is that possible.
Thanks.
Upvotes: 2
Views: 1798
Reputation: 4814
Query if the point intersects
or is within
a MultiPolygon:
var polygons = [polyA, polyB, polyC];
var multipolygon = { type: 'MultiPolygon', coordinates: polygons };
var results = query.where('loc').within().geometry(multipolygon);
Now, if you want to find which polygon contains the point, use JSTS:
// MongoDB query result
var point = results[0].loc;
// Convert geometries to JSTS
var geojsonReader = new jsts.io.GeoJSONReader();
jstsPoint = geojsonReader.read(point);
var jstsPolygons = polygons.map(function(polygon, index) {
jstsPolygon = geojsonReader.read({type: 'Polygon', coordinates: polygon});
jstsPolygon.__index = index; // or use whatever suits you best
return jstsPolygon;
});
// Find polygons containing point
jstsPolygons.filter(function(jstsPolygon){
return jstsPoint.within(jstsPolygon);
}).forEach(function(poly) {
console.log('Point is within polygon ' + poly.__index);
});
Here is a working example of JSTS using GeoJSON geometries.
Upvotes: 3