Search code examples
pythonbuffergisgeopandas

Geopandas not returning correct buffer in meters


I have a linestring geometry of which I want to calculate the corresponding buffer of 1 km in width. Despite setting the CRS i don't seem to be able to return the correct geometry

I'm running the following code to define the geodataframe


import pandas as pd
from shapely import LineString
import geopandas as gpd

test = pd.DataFrame(
    [["Test", LineString([(41.000, 18.583), (40.892, 18.952)])]], 
    columns=["Nome", "geometry"]
    )

test = gpd.GeoDataFrame(test, crs='EPSG:3003', geometry="geometry")

the crs is correctly set up and is in meters

>>> test.crs

<Projected CRS: EPSG:3003>
Name: Monte Mario / Italy zone 1
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: Italy - onshore and offshore - west of 12°E.
- bounds: (5.93, 36.53, 12.0, 47.04)
Coordinate Operation:
- name: Italy zone 1
- method: Transverse Mercator
Datum: Monte Mario
- Ellipsoid: International 1924
- Prime Meridian: Greenwich

however when i try to calculate the buffer i get this

>>> test.buffer(1000)

POLYGON ((-918.845 -261.947, -941.757 -166.523...

Buffer Image

as you can see the buffer is clearly wrong as the coordinates are not even valid coordinates (lat is -918.845!) what am I doing wrong? thanks in advance


Solution

  • That's because you're treating EPSG:3003 as a geographic CRS. Since your input is in lat/lon, you should initialize the GeoDataFrame with EPSG:4326, then use to_crs before making the buffer :

    gdf = gpd.GeoDataFrame(test, geometry="geometry", crs=4326).to_crs(3003)
    
    print(gdf.buffer(1000).to_crs(4326))
    
    # 0    POLYGON ((40.88408 18.94991, 40.88390 18.95066...
    # dtype: geometry
    

    Output :

    ax = gdf.to_crs(4326).plot(color="r")
    
    gdf.buffer(1000).to_crs(4326).plot(ax=ax)
    

    enter image description here