Search code examples
pythonpython-3.xpandaspolygongeopandas

How to create Polygon using 4 points?


I have CSV file, which contains the coordinates of points (more than 100 rows). Within CSV file there are 2 columns: Latitude, Longitude.
These points are the top left corners of some polygons. (squares)
All of the polygons has the same size (for example 100x100 meter).

Latitude               Longitude
56.37769816725615     -4.325049868061924
55.37769816725615     -3.325049868061924
51.749167440074324    -4.963575226888083 
...

I can load the CSV to dataframe, I can make points (or 4 points within row) from the coordinates with GeoPandas.
But how can I make Polygons for each row, which connects the 4 points?

Thanks for your help.

df = pd.read_csv('ExportPolyID.csv',nrows=10)
gdf= geopandas.GeoDataFrame(df,geometry=geopandas.points_from_xy(df.long, df.lat))
gdf['point2']= gdf.translate(2,2)
gdf['point3']=gdf.translate(3,3)
gdf['point4']=gdf.translate(4,4)
#After this I have 4 points for each row, but I can't connect them to create Polygons

Solution

  • If you want to define square in meters, make sure you are using projected CRS (http://geopandas.org/projections.html#re-projecting).

    Then you can use something like this (there might be more effective ways, but this one is explicit):

    from shapely.geometry import Polygon
    lat = [0, 2, 4]
    lon = [0, 2, 4]
    
    gdf = gpd.GeoDataFrame()
    gdf['lat'] = lat
    gdf['lon'] = lon
    
    dim = 1  # define the length of the side of the square
    geoms = []
    for index, row in gdf.iterrows():
        ln = row.lon
        lt = row.lat
        geom = Polygon([(ln, lt), ((ln + dim), lt), ((ln + dim), (lt - dim)), (ln, (lt - dim))])
        geoms.append(geom)
    
    gdf['geometry'] = geoms 
    

    This will generate square polygons from set coordinates of size dim x dim with point defined by given coords being top left.