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

如何在folium Draw插件中自动导出GeoJSON文件?

实现Folium Draw绘制后自动保存GeoJSON

Folium的Draw插件基于Leaflet.draw实现,默认需要手动点击导出按钮获取GeoJSON。要实现绘制后自动保存,你可以通过注入自定义JavaScript监听绘制/编辑事件,自动生成并保存GeoJSON文件。

修改后的代码示例

import folium
from folium.plugins import Draw
from folium import CustomJS

m = folium.Map(location=[45.523, -122.675], zoom_start=13)

# 配置Draw插件,根据需求调整可绘制要素类型
draw = Draw(
    export=True,
    filename='data.geojson',
    position='topleft',
    draw_options={
        'polyline': False,
        'circlemarker': False,
        'polygon': True,  # 开启多边形绘制(根据你的需求修改)
        'marker': False,
        'rectangle': False
    },
    edit_options={'poly': {'allowIntersection': False}}
)
draw.add_to(m)

# 注入自定义JS,实现自动导出逻辑
auto_export_js = """
const drawControl = window.drawControl;
const map = window.map;

// 定义自动导出GeoJSON的函数
function autoExportGeoJSON() {
    // 获取当前所有绘制的要素
    const features = drawControl._toolbars.draw._geojsonLayer.toGeoJSON().features;
    const geojson = {
        type: "FeatureCollection",
        features: features
    };
    // 转换为JSON字符串并生成下载链接
    const dataStr = JSON.stringify(geojson, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', 'auto_saved_data.geojson');
    linkElement.click();
}

// 监听绘制完成事件
map.on('draw:created', () => setTimeout(autoExportGeoJSON, 100));
// 监听编辑完成事件(可选)
map.on('draw:edited', () => setTimeout(autoExportGeoJSON, 100));
// 监听要素删除事件(可选)
map.on('draw:deleted', () => setTimeout(autoExportGeoJSON, 100));
"""

CustomJS(code=auto_export_js).add_to(m)

m

代码说明

  • 这段代码通过CustomJS向地图注入前端逻辑,监听Leaflet.draw的核心事件:
    • draw:created:绘制新要素完成时触发
    • draw:edited:编辑已有要素完成时触发
    • draw:deleted:删除要素时触发
  • 每次事件触发后,会自动收集当前所有绘制的要素,生成标准GeoJSON格式的文件并触发浏览器下载,无需手动点击导出按钮。
  • 注意调整draw_options中的配置,比如你原代码关闭了polygon,如果需要绘制多边形,要将其设为True。

后端保存场景(可选)

如果是在Web应用(如Flask/Django)中,你可以把前端的下载逻辑换成AJAX请求,将GeoJSON数据发送到后端接口,由后端保存为文件。示例修改如下:

function autoExportGeoJSON() {
    const features = drawControl._toolbars.draw._geojsonLayer.toGeoJSON().features;
    const geojson = {
        type: "FeatureCollection",
        features: features
    };
    const dataStr = JSON.stringify(geojson, null, 2);
    
    // 发送到后端接口
    fetch('/api/save-geojson', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: dataStr,
    })
    .then(res => res.json())
    .then(data => console.log('保存成功:', data))
    .catch(err => console.error('保存失败:', err));
}

内容的提问来源于stack exchange,提问作者Reza MN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:05:18