Reputation: 1365
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.
Upvotes: 1
Views: 1849
Reputation: 698
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])
Upvotes: 1
Reputation: 64443
If you don't mind a dependency on GDAL/OGR, you can use this:
geom = ogr.CreateGeometryFromWkt(wkt)
extent = geom.GetEnvelope()
The extent will be a tuple: (366247.0, 383331.0, 156971.0, 174054.0)
Having the extra dependency is of course a downside, but OGR does handle the parsing/validation for you.
Upvotes: 1