Osmosis/Polygon Filter File Python Parsing Geodjango

From OpenStreetMap Wiki
Jump to: navigation, search

Function to convert a textual POLY file to Geodjango MultiPolygon.

from django.contrib.gis.geos import MultiPolygon, Polygon

def parse_poly2(lines):
        Parse an Osmosis polygon filter file.

        Accept a sequence of lines from a polygon file, return a django.contrib.gis.geos.MultiPolygon object.


        Adapted from http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Python_Parsing
    in_ring = False
    coords = []
    for (index, line) in enumerate(lines):
        if index == 0:
            # first line is junk.
        elif in_ring and line.strip() == 'END':
            # we are at the end of a ring, perhaps with more to come.
            in_ring = False
        elif in_ring:
            # we are in a ring and picking up new coordinates.
            ring.append(map(float, line.split()))
        elif not in_ring and line.strip() == 'END':
            # we are at the end of the whole polygon.
        elif not in_ring and line.startswith('!'):
            # we are at the start of a polygon part hole.
            ring = coords[-1][-1]
            in_ring = True
        elif not in_ring:
            # we are at the start of a polygon part.
            ring = coords[-1][0]
            in_ring = True
    return MultiPolygon ( *(Polygon ( *polycoords ) for polycoords in coords) )