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

Folium加载GeoJSON填充颜色无法正常显示问题求助

解决Folium中GeoJSON填充颜色不显示的问题

问题原因

你的代码存在三个核心问题:

  1. 样式参数命名错误:Folium使用下划线分隔的参数名(而非Leaflet原生的驼峰式),fillColor和fillOpacity不会被识别,导致填充样式未生效;
  2. 索引越界风险:GeoJSON中value属性值为1-10,而你的colors列表索引为0-9,直接用int(feature['properties']['value'])会导致最后一个元素索引越界;
  3. 无效参数:closed不是Folium支持的样式参数,属于冗余代码。

修正后的代码

import folium
import requests
import json

# Load GeoJSON data from the provided URL
url = "https://earthquake.usgs.gov/product/shakemap/us7000kufc/us/1699242609676/download/cont_mmi.json"
response = requests.get(url)
geojson_data = json.loads(response.text)

# Create a folium map centered around the first coordinate in the GeoJSON
mymap = folium.Map(location=[geojson_data['features'][0]['geometry']['coordinates'][0][0][1],
                              geojson_data['features'][0]['geometry']['coordinates'][0][0][0]],
                   zoom_start=10)

# Define colors based on the "value" property
colors = ['#a0e5ff', '#90f2ff', '#80ffff', '#80dfff', '#80bfff', '#809fff', '#8080ff', '#bf80ff', '#df80ff', '#ff80ff']

# Add GeoJSON layer to the map with different colors
folium.GeoJson(
    geojson_data,
    style_function=lambda feature: {
        # 修正参数名:fillColor → fill_color,fillOpacity → fill_opacity
        'fill_color': colors[int(feature['properties']['value']) - 1],
        'color': colors[int(feature['properties']['value']) - 1],
        'weight': 3,
        'fill_opacity': 0.5
    }
).add_to(mymap)

# Display the map
mymap

关键修改说明

  • 参数名修正:将fillColor改为fill_color、fillOpacity改为fill_opacity,这是Folium标准的样式参数命名方式,确保填充颜色和透明度被正确应用;
  • 索引修正:通过int(feature['properties']['value']) - 1将1-10的value值映射到0-9的列表索引,避免越界错误;
  • 移除无效参数:删除closed配置,该参数不属于Folium的样式配置项,无实际作用。

内容的提问来源于stack exchange,提问作者John Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:15:44