tecznotes
Michal Migurski's notebook, listening post, and soapbox. Subscribe to this blog. Check out the rest of my site as well.
Apr 25, 2012 10:25pm
polygonize it
If you need to make a bag of polygons from a selection of OpenStreetMap data, you would think that simply running shapely.ops.polygonize on the selection of linestrings is enough. In fact, polygonize needs for the line endings to coincide, and may not work as you would expect with OSM data. I scratched my head over this a bit after successfully using polygonize to handle TIGER data, until it occurred to me that TIGER is built to have lots and lot of little lines.
The trick is to split each linestring input to polygonize() into all its constituent segments, and then let the function do the reassembly work for you. Creating the polygons of Amsterdam above from metropolitan extract roads took just a few seconds. Here’s the polygonize.py script that does it, expecting GeoJSON input and producing GeoJSON output.
Comments (2)
Very cool Mike! Also, if you wanted to go the Quantum route, there is a tool called "Lines To Polygon" (Vector->Geometry Tools-> Lines to Polygon). Although it works great, I doubt it could run all of Amsterdam in a couple of seconds. Just another option.
Posted by Bobby S. on Thursday, April 26 2012 2:45pm UTC
Hi Bobby, I actually tried that function in QGIS and it gave me the same unexpected results as PostGIS and Shapely's polygonize without pre-processing the lines. I think they all use the same GEOS function under the hood, so it makes sense. The reason my function works where those don't is that it breaks T intersections from two lines into three, so that the polygonizer can do its work. I think it would have the same result if I saved out a GeoJSON file of the shattered linestrings and then polygonized them in QGIS.
Posted by Michal Migurski on Thursday, April 26 2012 3:17pm UTC
Sorry, no new comments on old posts.