You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python提取GeoJSON文件中多边形中心点经纬度用于plotly标注

实现方案

1. 依赖安装

你需要提前安装三个核心库,执行以下命令安装即可:
pip install geopandas plotly pandas

2. 中心点提取核心代码

import geopandas as gpd
import plotly.express as px
import plotly.graph_objects as go

# 加载法国省份边界GeoJSON数据
gdf = gpd.read_file("https://france-geojson.gregoiredavid.fr/repo/departements.geojson")
# 统一坐标系为WGS84,保证输出为标准经纬度
gdf = gdf.to_crs(epsg=4326)

# 计算每个区域的中心点
# 如果有飞地较多的省份,可替换为gdf.geometry.representative_point(),生成的点位会落在区域内更合理
gdf['centroid'] = gdf.geometry.centroid

# 拆分经纬度为单独字段
gdf['lon'] = gdf.centroid.x
gdf['lat'] = gdf.centroid.y

# 生成你需要的省份编码+经纬度列表,code为省份编码字段、nom为省份名称
centroid_list = gdf[['code', 'nom', 'lon', 'lat']].to_dict('records')
# 打印前5条校验结果
print(centroid_list[:5])

3. Plotly组合展示示例

如果你需要直接在choropleth地图上叠加省份编码标注,可以直接用以下代码实现:

# 绘制省份色块底图
fig = px.choropleth_mapbox(
    gdf,
    geojson=gdf.geometry,
    locations=gdf.index,
    color='code', # 此处可替换为你需要映射的业务数值字段
    mapbox_style='carto-positron',
    zoom=5,
    center = {"lat": 46.2276, "lon": 2.2137},
    opacity=0.3
)

# 叠加省份编码标注层
fig.add_trace(go.Scattermapbox(
    lon = gdf['lon'],
    lat = gdf['lat'],
    mode = 'text',
    text = gdf['code'],
    textfont=dict(size=12, color='black'),
    showlegend=False
))

fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

注意事项

  • 计算中心点前必须统一坐标系为EPSG:4326,否则输出的坐标不是标准经纬度,无法在mapbox地图上正确展示
  • 如遇中心点落在区域外的特殊情况,替换centroid为representative_point()即可解决

内容的提问来源于stack exchange,提问作者Jc LE BERRE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 19:36:01