Reputation: 531
There is already few existing questions about this topic, but I unfortunately did not find something that could fix my problem.
I have a point Lat, Long coordinate i.e. Lat= 10 and Long = 10. I want to create a shape file of a 0.5 degree bounding box around this point, so the bounding box should be as follow:
Does anyone knows how to do that in Python?
Upvotes: 5
Views: 9741
Reputation: 103
And here is an implementation of Bruno Carballo's answer that applies it to en entire DataFrame:
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
# function to return polygon
def bbox(vec):
long0, lat0, lat1, long1 = vec[0], vec[1], vec[2], vec[3]
return Polygon([[long0, lat0],
[long0,lat1],
[long1,lat1],
[long1, lat0]])
def extentPolygon(df):
return(
pd.DataFrame({'geometry' : df[['ext_min_x','ext_min_y','ext_max_y','ext_max_x']].apply(bbox, axis = 1)})
)
df = pd.DataFrame({'ext_min_x' : [9.75, 9.78], 'ext_max_x' : [10.25, 10.28],
'ext_min_y' : [9.75, 9.78], 'ext_max_y' : [10.25, 10.28]})
df = extentPolygon(df)
After which you can easily turn the resulting DataFrame into a GeoDataFrame:
df_gp = gdp.GeoDataFrame(df)
Upvotes: 0
Reputation: 828
I want to enchance Bruno Carballo's code. I hope it will easier for you
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
# function to return polygon
def bbox(long0, lat0, lat1, long1):
return Polygon([[long0, lat0],
[long1,lat0],
[long1,lat1],
[long0, lat1]])
test = bbox(9.75, 9.75, 10.25, 10.25)
gpd.GeoDataFrame(pd.DataFrame(['p1'], columns = ['geom']),
crs = {'init':'epsg:4326'},
geometry = [test]).to_file('poly.shp')
Upvotes: 5
Reputation: 1196
Here's one way to do it using shapely, geopandas and pandas:
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
def bbox(lat,lng, margin):
return Polygon([[lng-margin, lat-margin],[lng-margin, lat+margin],
[lng+margin,lat+margin],[lng+margin,lat-margin]])
gpd.GeoDataFrame(pd.DataFrame(['p1'], columns = ['geom']),
crs = {'init':'epsg:4326'},
geometry = [bbox(10,10, 0.25)]).to_file('poly.shp')
Upvotes: 11