如何在Leaflet地图中添加Shapefile/GeoJSON边界?
Leaflet绘制单个选区边界指引
第一步:提取单个选区的GeoJSON
如果不想加载完整的所有选区数据,先从原Shapefile里提取目标选区的GeoJSON,用你熟悉的GeoPandas就能搞定:
import geopandas as gpd # 读取原Shapefile文件 gdf = gpd.read_file("你的选区Shapefile路径.shp") # 替换成你要筛选的条件,比如根据选区名称列(比如列名是electorate_name) target_data = gdf[gdf["electorate_name"] == "你要的选区名称"] # 转换为WGS84坐标系(Leaflet默认用这个) target_data = target_data.to_crs(epsg=4326) # 保存为单独的GeoJSON target_data.to_file("single_electorate.geojson", driver="GeoJSON")
如果没有Python环境,用QGIS也能做:导入Shapefile后,用"选择特征"工具选中目标选区,然后右键导出为GeoJSON,导出时选择WGS84坐标系。
第二步:Leaflet实现代码
创建一个HTML文件,按以下步骤编写:
- 准备Leaflet的本地资源:从Leaflet官网下载样式文件(leaflet.css)和脚本文件(leaflet.js),放在和HTML同目录下。
- 编写HTML结构和地图逻辑:
<!DOCTYPE html> <html> <head> <title>单个选区边界</title> <link rel="stylesheet" href="leaflet.css" /> <script src="leaflet.js"></script> <style> #map { height: 600px; width: 100%; } </style> </head> <body> <div id="map"></div> <script> // 初始化地图,设置默认中心为你所在州的大致坐标(比如昆士兰州中心:[-27.4698, 153.0251]) const map = L.map('map').setView([-27.4698, 153.0251], 7); // 添加底图(这里用OpenStreetMap的瓦片,也可以换成你自己的离线底图) L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); // 加载并渲染单个选区的GeoJSON fetch('single_electorate.geojson') .then(res => res.json()) .then(geoData => { // 自定义边界样式 const layerStyle = { color: '#2c3e50', weight: 2, fillColor: '#3498db', fillOpacity: 0.3 }; // 创建GeoJSON图层并添加到地图 L.geoJSON(geoData, { style: layerStyle }).addTo(map); // 自动调整地图视野到选区范围 const bounds = L.geoJSON(geoData).getBounds(); map.fitBounds(bounds); }); </script> </body> </html>
可选:直接加载完整GeoJSON后筛选
如果不想单独提取,也可以直接加载所有选区的GeoJSON,然后在前端筛选目标选区:
fetch('all_electorates.geojson') .then(res => res.json()) .then(allData => { // 根据属性筛选目标选区,替换成你的属性名和值 const targetFeature = allData.features.find(f => f.properties.electorate_name === "目标选区名称"); const targetGeoJSON = { type: "FeatureCollection", features: targetFeature ? [targetFeature] : [] }; if (targetGeoJSON.features.length > 0) { L.geoJSON(targetGeoJSON, { style: layerStyle }).addTo(map); map.fitBounds(L.geoJSON(targetGeoJSON).getBounds()); } });
注意事项
- 确保GeoJSON是WGS84(EPSG:4326)坐标系,否则地图会错位。
- 如果本地加载GeoJSON遇到跨域问题,用本地服务器打开HTML(比如Python的
python -m http.server),不要直接双击打开。
内容的提问来源于stack exchange,提问作者Alasdair
相关产品推荐
相关产品推荐

