What's the best way to determine if a point is within a certain distance of a GEOJSON polygon? Should one use TurfJS buffer method (https://github.com/Turfjs/turf-buffer#turf-buffer)? Can one perform queries on the buffered polygon?
It's clear to me one could us the TurfJS' inside method (https://github.com/Turfjs/turf-inside) to determine whether a point is within a polygon. I'm just curious what the best approach would be for finding whether or not a point is inside of a buffered polygon.
For example: I have a number of neighborhoods provided as a GEOJSON polygon files. I also have a set of locations/addresses for employees (already geocoded to lat/long coordinates). What would be the best way to see whether or not my employees live within 10 miles of a given neighborhood polygon?
Answer
This really depends on a number of factors.
- Are you talking about a large number of features? Do you have 100 neighborhoods and 1000 point locations, or a thousand times that number?
- Is your precision requirement high enough that you'll need to take Great Circle calculations into account? At less than 10 miles the error will be around 10-30 meters, depending on your latitude (see 2).
If either of the above are true, then you'd be much better off parsing the GeoJSON into a spatial database and making the calculations from there. MongoDB offers some geospatial capability http://docs.mongodb.org/manual/core/2dsphere/ without having to mess around with GeoJSON parsing, but you'd have to play around with some of the spatial query operators to find something that suits. The other more established Spatial databases like PostGIS and Oracle will have more tools for the job (e.g. Oracle's SDO_WITHIN_DISTANCE), but you'll have more work getting up and running.
If you don't have loads of features and you're not worried about the great circle errors, then you could try using JSTS Topology Suite to help.
Here's a basic example. You'll need to work to calculate the basic lat/lng distances involved.
var tolerance = 10;
var geojsonPolygon = {
"type": "Polygon",
"coordinates": [
[
[10.0, 10],
[20.0, 10],
[20.0, 20],
[10.0, 20],
[10.0, 10]
]
]
};
var geojsonPoint = {
"type": "Point",
"coordinates":
[0, 0]
};
var reader = new jsts.io.GeoJSONReader();
var polygon = reader.read(geojsonPolygon);
var point = reader.read(geojsonPoint);
var ptDist = new jsts.algorithm.distance.PointPairDistance();
jsts.algorithm.distance.DistanceToPoint.computeDistance(polygon,point.getCoordinate(),ptDist);
if(ptDist.getDistance() < tolerance){
// It's within 10
} else {
// It's further than 10
};
Hope that helps.
No comments:
Post a Comment