Sunday, 26 May 2019

leaflet - Convert GeoJSON with multiple Polygons and MultiPolygons into single MultiPolygon?



Is this even possible?


I have a GeoJSON file with multiple polygons and multipolygons, and I need to set styling on them (in Leaflet.js). I'd like to create a single, large MultiPolygon from the individual MultiPolygons and Polygons.


How can I do this (preferably in Node.js or at the Linux command-line)?


Things get really tricky when there's a MultiPolygon consisting of Polygons AND other Multipolygons.


Can this be "cleaned up" without any loss of information?



Answer



You could do this using Javascript Topology Suite which will work with Node.js. Start with an empty MultiPolygon (or the first geometry in your collection) and union this with each (Multi)Polygon in your collection. You can only have one format for the whole collection, obviously, as properties are one to one with the geometry in the GeoJSON. Here are some jsts/node.js examples.


There is also a GeoJSON parser in jsts, which will return a jsts geometry. So putting it all together, you would do something along the lines of:


var jsts = require("jsts");


var reader = new jsts.io.GeoJSONParser();

//read your geometries
var geoms = reader.read(geojson);

//grab the first one
var multipolygon = geoms[0];

//union with all the others
for (var x=1; x < geoms.length ; x++){

multipolygon = multipolygon.union(geoms[x]);
}

This is untested, but the general idea should work. You would have to recreate the GeoJSON with properties afterwards, but this should be easy with the built in JSON methods in Javascript.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...