Select Page

Spatial task

Generate an interactive web map using leaflet for the shown data layer.

Dataset

The Pennsylvania county boundaries downloaded from OpenStreetMap

Result

Generated interactive web map (click to open): PA_counties_map

Generated web map displayed directly in the GIS Copilot.

Geoprocessing workflow

 

Generated code

# Importing necessary libraries
import os
import geopandas as gpd
import folium

def generate_interactive_web_map():
# Step 1: Load the shapefile using GeoPandas
shapefile_path = “C:/Users/17036/Downloads/DEMO/PA_counties.shp”
counties_gdf = gpd.read_file(shapefile_path)

# Ensure the input data CRS is handled as described in the data properties
counties_gdf = counties_gdf.set_crs(epsg=4269)

# Step 2: Reproject the GeoDataFrame to WGS 84 (EPSG:4326) which is a common CRS for web mapping
counties_gdf = counties_gdf.to_crs(epsg=4326)

# Step 3: Get the centroid location of Pennsylvania to focus the map
pa_centroid = counties_gdf.dissolve().geometry.centroid.iloc[0]

# Step 4: Create a Folium map centered at Pennsylvania centroid
m = folium.Map(location=[pa_centroid.y, pa_centroid.x], zoom_start=7)

# Step 5: Add the GeoDataFrame to the map with correct tooltip fields
folium.GeoJson(
counties_gdf,
name=“PA Counties”,
tooltip=folium.GeoJsonTooltip(fields=[‘NAME’, ‘STATE_NAME’],
aliases=[‘County Name’, ‘State Name’],
localize=True)
).add_to(m)

# Step 6: Add layer control
folium.LayerControl().add_to(m)

# Step 7: Save the map as an HTML file in the specified output directory
output_directory = “C:/Users/17036/Downloads/PACounties”
os.makedirs(output_directory, exist_ok=True)

html_output_path = os.path.join(output_directory, “PA_counties_map.html”)

# To avoid overwriting, check if file exists and append a number if necessary
base_html_output_path = html_output_path
count = 1
while os.path.exists(html_output_path):
html_output_path = base_html_output_path.replace(‘.html’, f‘_{count}.html’)
count += 1

m.save(html_output_path)
# Output the path to the saved HTML file
print(html_output_path)

# Execute the function
generate_interactive_web_map()