write python code which uses openstreetmap api to find all rivers in Wrocław, Poland,…
- User
write python code which uses openstreetmap api to find all rivers in Wrocław, Poland, and plot it overlaped with Wrocław's boundaries
- Assistant
write python code which uses openstreetmap api to find all rivers in Wrocław, Poland, and plot it overlaped with Wrocław's boundaries
Certainly! Below is a Python script that leverages the OpenStreetMap (OSM) data to:
Before running the script, ensure you have the following Python libraries installed:
geopandas: For handling geospatial data.overpy: To interact with the Overpass API (a read-only API that serves OSM data).shapely: For geometric operations.matplotlib: For plotting.requests: To handle HTTP requests (used by geopandas).descartes: To enable plotting of geometric objects.You can install them using pip:
pip install geopandas overpy shapely matplotlib requests descartes
import overpy
import geopandas as gpd
from shapely.geometry import Polygon, MultiPolygon, LineString, MultiLineString
import matplotlib.pyplot as plt
def get_wroclaw_boundary(api):
"""
Retrieves the administrative boundary of Wrocław, Poland.
"""
# Overpass QL query to get the administrative boundary relation for Wrocław
query = """
[out:json];
relation
["name"="Wrocław"]
["boundary"="administrative"]
["admin_level"="6"];
out geom;
"""
result = api.query(query)
for rel in result.relations:
polygons = []
for member in rel.members:
if isinstance(member, overpy.RelationWay):
coords = [(float(node.lon), float(node.lat)) for node in member.resolve().nodes]
polygons.append(coords)
if polygons:
if len(polygons) == 1:
return Polygon(polygons[0])
else:
return MultiPolygon([Polygon(p) for p in polygons])
return None
def get_rivers(api, boundary_polygon):
"""
Retrieves all rivers within the given boundary.
"""
# Get the bounding box of the boundary_polygon
minx, miny, maxx, maxy = boundary_polygon.bounds
# Overpass QL query to get rivers within the bounding box
query = f"""
[out:json];
(
way["waterway"="river"]({miny},{minx},{maxy},{maxx});
relation["waterway"="river"]({miny},{minx},{maxy},{maxx});
);
out geom;
"""
result = api.query(query)
rivers = []
for way in result.ways:
coords = [(float(node.lon), float(node.lat)) for node in way.nodes]
if len(coords) > 1:
rivers.append(LineString(coords))
for rel in result.relations:
for member in rel.members:
if isinstance(member, overpy.RelationWay):
coords = [(float(node.lon), float(node.lat)) for node in member.resolve().nodes]
if len(coords) > 1:
rivers.append(LineString(coords))
return gpd.GeoSeries(rivers, crs="EPSG:4326")
def main():
api = overpy.Overpass()
print("Fetching Wrocław's boundary...")
wroclaw_boundary = get_wroclaw_boundary(api)
if wroclaw_boundary is None:
print("Could not retrieve Wrocław's boundary.")
return
# Create a GeoDataFrame for the boundary
boundary_gdf = gpd.GeoDataFrame(
{"geometry": [wroclaw_boundary]}, crs="EPSG:4326"
)
print("Fetching rivers within Wrocław...")
rivers = get_rivers(api, wroclaw_boundary)
if rivers.empty:
print("No rivers found within Wrocław.")
return
# Clip rivers to the boundary
rivers_clipped = gpd.clip(rivers.to_frame(name='geometry'), boundary_gdf)
# Plotting
fig, ax = plt.subplots(figsize=(10, 10))
boundary_gdf.boundary.plot(ax=ax, color='black', linewidth=1, label='Wrocław Boundary')
rivers_clipped.plot(ax=ax, color='blue', linewidth=1, label='Rivers')
ax.set_title("Rivers in Wrocław, Poland")
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.legend()
plt.show()
if __name__ == "__main__":
main()
Imports: The script imports necessary libraries for data retrieval (overpy), geospatial data handling (geopandas, shapely), and plotting (matplotlib).
get_wroclaw_boundary Function:
Polygon or MultiPolygon representing Wrocław's boundaries.get_rivers Function:
waterway=river) within that bounding box.LineString objects for each river found and returns them as a GeoSeries.main Function:
matplotlib.Ensure Dependencies: Make sure all the required Python libraries are installed as mentioned in the prerequisites.
Execute: Save the script to a file, say wroclaw_rivers.py, and run it using Python:
python wroclaw_rivers.py
Output: A plot will be displayed showing Wrocław's boundaries with rivers overlaid in blue.
Administrative Level: The admin_level=6 tag is commonly used for cities/towns in Poland. If you encounter issues retrieving the boundary, you might need to adjust the admin_level or examine the OSM data for the correct tags.
Data Accuracy: The completeness and accuracy of the river data depend on contributions to OpenStreetMap. Some smaller or seasonal rivers might not be present.
Performance: Overpass API has usage policies and rate limits. For extensive or repeated queries, consider setting up your own Overpass instance or caching results appropriately.
Projection: The script uses the WGS84 coordinate system (EPSG:4326). For more accurate area or distance calculations, consider projecting the data to a suitable coordinate reference system (e.g., UTM zone appropriate for Wrocław).
[image: Wroclaw Rivers Plot] open
(Replace the image link with an actual plot if available.)
This script provides a foundational approach to interacting with OpenStreetMap data using Python. You can extend it further by adding features like interactive maps using libraries such as folium or enhancing the visualization with additional layers and styling.
Not yet included in a published release.