从 Leaflet 导出 GPX 文件

Export GPX file from Leaflet

我想做的是让用户通过在 Leaflet 中选择一些 GeoJson 功能来创建一个 GPX 文件。我这样做的方法是创建一个新的 GeoJson 层来存储所选特征,然后使用名为 togpx (https://github.com/tyrasd/togpx) 的插件将其转换为 gpx。现在我有一个gpx文件,但我不知道如何让用户下载它。有什么建议么?这是我的代码:

var GPXfile;
var trails = new L.GeoJSON.AJAX('data/trasee.geojson', {
    onEachFeature: function(feature, layer) {
        layer.on({
            click: function () {
                var selectedGeojson = {
                  "type": "FeatureCollection",
                  "features": [
                    {
                      "type": "Feature",
                      "properties": {
                       "name": "Rocka Rolla"
                      },
                      "geometry": {
                        "type": "LineString",
                        "coordinates": feature.geometry.coordinates
                      }
                    }]
                }
                GPXfile = togpx(selectedGeojson);
            }
        })
    }
}).addTo(map);

JsFiddle 可能有帮助:http://jsfiddle.net/pufanalexandru/20ara4qe/1/

你可以试试...

A link 触发下载:

<a href="#" download="MyTracks.gpx" id="exportGPX">Export to file</a>

一些javascript(你必须包括jquery):

$("#exportGPX").on('click', function (event) {

        // prepare the string that is going to go into the href attribute
        // data:mimetype;encoding,string
        data = 'data:application/javascript;charset=utf-8,' + encodeURIComponent(gpxData);

        // set attributes href and target in the <a> element (with id  exportGPX)
        $(this).attr({
            'href': data,
            'target': '_blank'
        });

        // let the click go through
    });

这里有一个例子:http://jsfiddle.net/FranceImage/vxe23py4/

注意:它适用于 Chrome,但您也应该尝试其他浏览器。