首页 > 解决方案 > 传单绘制 - toGeoJSON

问题描述

我还是 Leaflet 的新手,并且一直在自学。我使用 Leaflet Draw 库制作了一张效果很好的地图,我想添加一个函数,允许用户将绘制的特征保存到 GeoJSON 文件中。我已经尝试使用本指南,但我仍然没有任何运气。

我正在使用导出功能的按钮:

    <input type='button' id='export' value='Export Feature (.kml)' class='btn' />

具有以下主体:

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> ',
        osm = L.tileLayer(osmUrl, { maxZoom: 18, attribution: osmAttrib }),
        map = new L.Map('map', { center: new L.LatLng(-29.5, 24.85), zoom: 6 }),
        drawnItems = L.featureGroup().addTo(map);
L.control.layers({
    'Street': osm.addTo(map),
    "Satellite": L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: 'Tiles &copy; Esri</a>'
    })
}, {'Survey Area': drawnItems }, { position: 'topleft', collapsed: false }).addTo(map); 

    map.addControl(new L.Control.Draw({
    edit: {
        featureGroup: drawnItems,
        poly: {
            allowIntersection: false
        }
    },
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        }
    }
}));

map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;

    drawnItems.addLayer(layer);
}); 

document.getElementById('export').onclick = function(e) {
        // Extract GeoJson from featureGroup
        var data = featureGroup.toGeoJSON();

        // Stringify the GeoJson
        var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));

        // Create export
        document.getElementById('export').setAttribute('href', 'data:' + convertedData);
        document.getElementById('export').setAttribute('download','data.geojson');
    }

我认为问题出在 featureGroup 或 drawItems 上,但我就是想不通。

标签: htmlleafletgeojson

解决方案


推荐阅读