Search code examples
pythongdalwkt

Extract XY extent from WKT string


Using python, how can I extract the XY extent of a WKT polygon? I need it in gdal compatible format like: minx miny maxx maxy

So for example below, I'd need to convert wkt to be wkt_extent:

wkt = "Polygon ((366247 156971, 366247 174054, 383331 174054, 383331 156971, 366247 156971))"
# need xy bounding box coordinates of wkt, as shown below
wkt_extent = "366247 156971 383331 174054"

Please keep in mind that the wkt is not always a rectangle/square and is not always 'drawn' in a clockwise direction like the example wkt shown here.

SRID here is 27700 and units are in meters.


Solution

  • Assuming your WKT is passed as a string:

    def parse_geometry(geometry):
        regex = r'[0-9-\.]+'
        parsed_geom = re.findall(regex, geometry)
        parsed_geom = [float(i) for i in parsed_geom]
        return max(parsed_geom[::2]), min(parsed_geom[::2]), max(parsed_geom[1::2]), min(parsed_geom[1::2])