Methods: I'm currently using turf.js for geoprocessing as part of a broader mapping project; my workflow looks like this:
- Pull geojson of census tracts for an entire county
- Pull geojson tiles of water polygons from OSM for the county area
- Recursively pull the tracts and each water tile into a node script
- In the script,
turf.merge
the water tile into a single multipolygon - In the script, recursively
turf.intersect
each tract polygon against the water multipolygon - In the script,
turf.erase
the water area from the tract polygon if it intersects - Dump the water-erased tracts to file
Problem: As my process iterates through each water tile in step 3, it hits one particular tile and begins throwing this error:
/Users/wboykinm/github/tribes/processing/water/node_modules/turf/node_modules/turf-intersect/index.js:45
if(poly2.type === 'Feature') geom2 = poly2.geometry;
^
TypeError: Cannot read property 'type' of null
at Object.module.exports [as intersect] (/Users/wboykinm/github/tribes/processing/water/node_modules/turf/node_modules/turf-intersect/index.js:45:11)
at Object.<anonymous> (/Users/wboykinm/github/tribes/processing/water/piranha.js:26:14)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
. . . which continues for all subsequent iterations. As soon as the error occurs, the tracts geojson file is malformed and won't load in any viewer.
What's most perplexing is the fact that this error only occurs when I run all the tiles in sequence through the turf script. The script succeeds when I run just the offending tile, on its own. The script also results in malformed geojson if I merge all the water tiles into a single geojson file and turf.erase
it directly against the tracts file. An additional complication is that the entire procedure works fine if I combine the water tiles into one file, then take it over to QGIS and manually run a "difference" geoprocess; no errors, valid output geometry.
All the signs are pointing to a problem of invalid geometry, possibly related to the tile boundaries or the way I'm merging the water polygons. How can I find the bad geometry and repair it using the tools at hand (turf.js)?