Geographic Information Systems Asked by Jordy W on August 30, 2020
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.
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
For a polygon looking like this it will not find the longest line since there is no vertice top mid:
Answered by BERA on August 30, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP