0

I'm having a a GeoDataFrame of polygons. I want to find the maximum length of a straight line that can fit inside each polygon. You could call this the characteristic length of the polygon. The length I'm looking for is shown in below image. I took the image from this SE question, but they use POSTGIS and I would like to do this with Python GeoPandas.

Is this possible with GeoPandas? If yes, could somebody explain me how to do this? Thanks in advance!

I tried polygondf.length, but this gives me the length of the perimeter, which is not what I'm looking for.

Maximum length in Polygon

2

An approximation since it will only measure distances between existing vertices:

import geopandas as gpd
from shapely.geometry import LineString, mapping
from itertools import combinations
import re

df = gpd.read_file('/home/bera/GIS/Data/testdata/longest_line2.shp')

longest_lines = []
for g in list(df.geometry):
    all_coords = str(mapping(g)["coordinates"]) #https://gis.stackexchange.com/questions/287306/list-all-polygon-vertices-coordinates-using-geopandas
    all_xys = re.findall("\d+\.\d+", all_coords) #I know this is ugly, but it works in extracting floats from nested tuples
    all_xys = zip(all_xys[::2],all_xys[1::2])
    lines = []
    for p1,p2 in combinations(all_xys,2): #For all combinations of polygon vertices create a line
        line = LineString([(float(p1[0]),float(p1[1])), (float(p2[0]),float(p2[1]))])
        line = line.intersection(g) #To only include the line inside polygon
        lines.append(line)
    longest_lines.append(max(lines, key=lambda x: x.length)) #Find longest line

df.geometry=longest_lines #Replace polygon geometris with lines
df.to_file('/home/bera/GIS/Data/testdata/longest_lines2.shp') #Save

enter image description here

For a polygon looking like this it will not find the longest line since there is no vertice top mid: enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.