Home > Blockchain >  Calculate the length of a polygon in python
Calculate the length of a polygon in python

Time:01-25

I have a geopandas dataframe:

    lon           lat         geometry
0   31.269899   30.072927   POINT (30.07293 31.26990)
1   31.269413   30.073965   POINT (30.07397 31.26941)
2   31.268751   30.073629   POINT (30.07363 31.26875)
3   31.269287   30.073505   POINT (30.07351 31.26929)
4   31.269081   30.074694   POINT (30.07469 31.26908)

I created a polygon out of all of those points like this:

import geopandas as gpd
from shapely.geometry import Point, Polygon

gdf = gpd.GeoDataFrame(df,geometry = gpd.points_from_xy(df['lat'],df['lon']))
points = [x for x in gdf.geometry]
polygon = Polygon([[p.x, p.y] for p in points])
print(polygon)

The output is a polygon:

POLYGON ((30.072927474975586 31.269899368286133, 30.073965072631836 31.269412994384766, 30.07362937927246 31.26875114440918, 30.073505401611328 31.269287109375, 30.07469367980957 31.269081115722656, 30.073972702026367 31.269569396972656, 30.074140548706055 31.269651412963867, 30.07431983947754 31.26882553100586,...)

How can I get the length in meters? to get the distance between the first retailer for example and the last retailer on the map, so that it takes a shape of a line that you can measure.

I tried this code:

polygon.length * 0.000621371

It gave : 5.04009394506436e-05

Which is wrong.

What am I doing wrong here guys?

CodePudding user response:

How can I get the length in meters?

The unit distance between coordinates (lat, lon) is kilometers so to convert in meters just multiply by 1000:

>>> polygon.length * 1000
5.592554141703987  # meters

polygon.length * 0.000621371

Do you want the distance in meters or miles?

CodePudding user response:

Another way to do it is using geopy and it's function called distance, adding some changes to your code. geopy distance documentation

Usage:

geopy.distance.distance([from.lon, from.lat], [to.lon, to.lat]).km

Not sure if there's a built-in function to convert to meters, but having kilometers it should be easy to do.

  • Related