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

Python中如何保存folium.PolyLine对象?pickle保存遇报错

解决folium.PolyLine对象无法用pickle保存的问题

为什么pickle不行

folium的PolyLine等可视化对象内部关联了大量框架上下文资源(比如回调函数、地图实例引用),这类包含动态函数引用的对象无法被pickle序列化,因此会抛出PicklingError。

可行方案

方案1:保存原始坐标点(推荐)

生成PolyLine耗时的核心通常是坐标点的计算/解析过程,直接保存坐标点列表即可,后续能快速重建PolyLine:

  • 保存坐标点(用JSON格式,兼容性更强):
import json
import os

# points为你的轨迹坐标列表,格式如[(lat1, lon1), (lat2, lon2), ...]
save_path = os.path.join("data", "precomputed_points.json")

with open(save_path, "w", encoding="utf-8") as f:
    json.dump(points, f)
  • 加载并生成PolyLine:
with open(save_path, "r", encoding="utf-8") as f:
    saved_points = json.load(f)
precomputed_line = folium.PolyLine(saved_points, color="red", weight=3)

方案2:保存为GeoJSON格式

如果需要保留PolyLine的样式配置,可以将其转换为GeoJSON格式保存,后续通过folium.GeoJson还原:

  • 保存PolyLine为GeoJSON:
precomputed_line = folium.PolyLine(points, color="red", weight=3)
geojson_str = precomputed_line.to_json()

save_path = os.path.join("data", "precomputed_trajectory.geojson")
with open(save_path, "w", encoding="utf-8") as f:
    f.write(geojson_str)
  • 加载GeoJSON并重建:
import json

with open(save_path, "r", encoding="utf-8") as f:
    geojson_data = json.load(f)
precomputed_line = folium.GeoJson(
    geojson_data,
    style_function=lambda x: {
        "color": x["properties"]["color"],
        "weight": x["properties"]["weight"]
    }
)

内容的提问来源于stack exchange,提问作者Lk Ncll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:20:21