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

如何在Folium中绘制大型.shp文件的部分图形以优化性能

解决大型SHP文件生成HTML体积过大的问题

当读取完整大型SHP文件后生成的HTML超过600MB、无法正常加载时,可通过只绘制部分图形来减小文件体积,以下是几种可行方案:

1. 随机采样部分要素

直接从SHP文件中随机抽取指定数量或比例的要素,大幅减少数据量。

修改读取SHP文件的代码:

# 方式1:抽取固定数量的要素(比如1000个)
map_shape = gpd.read_file("some_huge_shape_file.shp").sample(n=1000, random_state=42)

# 方式2:抽取指定比例的要素(比如10%)
map_shape = gpd.read_file("some_huge_shape_file.shp").sample(frac=0.1, random_state=42)
  • n:指定要抽取的要素数量,根据需求调整
  • frac:指定抽取的比例(0到1之间)
  • random_state:固定随机种子,保证每次采样结果一致,方便调试

2. 按属性筛选要素

如果只需要特定类别的图形,可根据SHP文件的属性字段筛选。比如只保留TYPE为特定值的要素:

map_shape = gpd.read_file("some_huge_shape_file.shp")
# 筛选TYPE字段等于"Residential"的要素(替换为你的目标属性值)
map_shape = map_shape[map_shape['TYPE'] == "Residential"]

3. 按空间范围筛选要素

如果只需要地图某一区域内的图形,可通过边界框筛选落在目标区域内的要素:

from shapely.geometry import box

map_shape = gpd.read_file("some_huge_shape_file.shp")
# 定义目标区域的经纬度范围(左、下、右、上)
target_bbox = box(-114, 52, -112, 54)
# 创建边界框的GeoDataFrame,确保坐标系与SHP文件一致
bbox_gdf = gpd.GeoDataFrame({'geometry': [target_bbox]}, crs=map_shape.crs)
# 筛选落在边界框内的要素
map_shape = gpd.sjoin(map_shape, bbox_gdf, predicate='within')

修改后的完整代码示例(随机采样版本)

import folium
from folium import plugins
import geopandas as gpd
import random

m = folium.Map([53, -113], zoom_start=8, control_scale=True)
minimap = plugins.MiniMap()
m.add_child(minimap)

# 读取SHP文件并随机采样1000个要素
map_shape = gpd.read_file("some_huge_shape_file.shp").sample(n=1000, random_state=42)

def random_html_color():
    # 修正原代码错误:RGB值范围是0-255,而非0-256
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    return '#%02x%02x%02x' % (r, g, b)

def style_fcn(x):
    return { 'fillColor': random_html_color(), 'opacity': 0.1 }

def highlight_fcn(x):
    return { 'fillColor': '#ff0000' }

folium.GeoJson(
    data=map_shape,
    overlay=True,
    popup_keep_highlighted=True,
    style_function=style_fcn,
    highlight_function=highlight_fcn,
    tooltip=folium.GeoJsonTooltip(fields=['DESREP']),
    popup=folium.GeoJsonPopup(fields=['TYPE', 'NUMBER'])
).add_to(m)

# 保存生成的地图
m.save('smaller_map.html')

内容的提问来源于stack exchange,提问作者Ajay Ganesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:03:17