Search code examples
javascriptturfjs

Turfjs Point In Polygon always returns false


I'm using Google maps API that geolocates the user and, if they are in the city of Los Angeles, will tell them what LAPD reporting district they are in. I have a geojson overlay of the reporting districts (RD's) that's loading from here.

I want to get the geolocated coordinates, and use Turfjs's booleanPointInPolygon to determine if it's in an RD and if so, return that RD.

But no matter what I do, the turfjs function always returns false even though I'm clearly in an RD/Polygon.

I downloaded the geojson file and import it locally as a regular json file. Here is my function:

    getRd() {
            const repdist = require("../assets/LAPD_Reporting_Districts.json");
            let point = turf.point([34.05350702472784, -118.24291762202074]);
            var poly;
            repdist.features.forEach(rd => {
                poly = turf.polygon(rd.geometry.coordinates);
                var found = turf.booleanPointInPolygon(point, poly);
                console.log("found: ", found);
            });

As far as I can tell, the turf.point and turf.polygon array are properly formed and there are no errors on execution. I've stepped through the turf function and everything seemed fine.

Given the coords in the code sample (LA City Hall, which is in RD 124), I would expect the result to return true, but "found" returns 1135 falses.


Solution

  • I'd suggest checking two things:

    • The turf.point coordinate must be Lon,Lat instead of Lat,Lon. This might be the issue because -118 is not a valid latitude. Lon,Lat is a very common convention.

    • Also check the value passed in to booleanPointInPolygon The documentation shows the coordinate arrays being wrapped in two arrays, not just one.