Search code examples
node.jsd3.jspolygonr-treepoint-in-polygon

Find in which polygon a GeoJSON point lies in, in NodeJS


Given a defined (lat, lon) geo-point I'm trying to find in which polygon this point lies in. I suppose iterating over all the polygons is not efficient. Is there available any function or library for NodeJS that does this?

const polygon = getPolygonFromPoint(FeatureCollection, x, y);

There are no overlapping polygons, actually I'm using this to detect in which district of a certain country a defined GPS coordinates point lies in.


Solution

  • I implemented that with the library polygon-lookup

    const PolygonLookup = require('polygon-lookup')
    const featureCollection = {
        type: 'FeatureCollection',
        features: [{
            type: 'Feature',
            properties: { id: 'bar' },
            geometry: {
                type: 'Polygon',
                coordinates: [ [ [ 0, 1 ], [ 2, 1 ], [ 3, 4 ], [ 1, 5 ] ] ]
            }
        }]
    }
    var lookup = new PolygonLookup(featureCollection)
    var poly = lookup.search(1, 2)
    console.log(poly.properties.id) // bar