eLlobregat
eLlobregat

Reputation: 29

Export GPX route from leaflet map

I'm trying to find a way of producing a GPX string from a Leaflet map so I can then save it into my DB. I am using Leaflet Routing Machine to create the route and then display it on an embedded map. So far, I found many ways to import a GPX to Leaflet but I cannot figure out a way to do the opposite.

So far, my (simplified) code to display the map and generate the route is as it follows:

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <script src="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.js"></script>
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>




<div id="map" class="map"></div>
        



<style>
        .map {
            position: absolute;
            width: 50%;
            height: 50%;
            justify-content: right;         
        }
</style>



<script>
            var map = L.map('map').
            setView([40.416729,-3.703339], 5);
                
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
            
            L.Routing.control({
                routeWhileDragging: true,
                geocoder: L.Control.Geocoder.nominatim()    
            }).addTo(map);
        
</script> 

Upvotes: 0

Views: 1316

Answers (2)

shin2
shin2

Reputation: 1

How about this?

/* https://www.liedman.net/leaflet-routing-machine/tutorials/integration/ */
.on('routesfound', function(e) {
    GeoJsonCode = L.Routing.routeToGeoJson(e.routes[0]);
    //console.log(GeoJsonCode);

})       



    function ExportGPX(){
    let outputGpxText;
    let sp2 = '  ';
    let fileName = 'abcdefg';
    let trackName = 'hijklml';
    let elevFlag = false;

    if(typeof GeoJsonCode !== "undefined"){ // undefined check!
        //ファイルの中身をJSON形式に変換する
        let track = JSON.parse(GeoJsonCode);

            // https://stackoverflow.com/questions/51397890/how-to-use-polyline-decorator-in-leaflet-using-geojson-line-string
            track.features
                .filter(function (feature) { return feature.geometry.type == "LineString" })
                .map(function (feature) {

                    let textGpx = '<?xml version="1.0" encoding="UTF-8"?>' + '\n' +
                    '<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/0" version="1.1" author="signpost - https://signpost.mydns.jp/">' + '\n' +
                    '<metadata></metadata>' + '\n' +
                    '<trk>' + '\n' +
                    '<name>' + trackName + '<name>' + '\n' +
                    '<desc></desc>' + '\n' +
                    '<trkseg>' + '\n';
          
                    let coordinates = feature.geometry.coordinates;
            
                    if (elevFlag) {  // 標高が有る場合                     
                        coordinates.forEach(function (coordinate, i) {
                            textGpx = textGpx + sp2 + '<trkpt lat="' + coordinate[1] + '" lon="' + coordinate[0] + '">';
                            textGpx = textGpx + '<ele>' + coordinate[2] + '</ele>';
                            textGpx = textGpx + '</trkpt>' + '\n';
                        })
                    } else{ // 標高が無い場合
                        coordinates.forEach(function (coordinate, i) {
                            textGpx = textGpx + sp2 + '<trkpt lat="' + coordinate[1] + '" lon="' + coordinate[0] + '">';
                            textGpx = textGpx + '<ele></ele>';
                            textGpx = textGpx + '</trkpt>' + '\n';
                        })
                    }
                    textGpx = textGpx + '</trkseg></trk>' + '\n' + '</gpx>'

                    //console.log(textGpx);
                    outputGPXstyle = textGpx;
                })

            // Code Export >>>>>
            /* https://qiita.com/kerupani129/items/99fd7a768538fcd33420
            ※ [0].click():jQuery オブジェクトの [0] は HTMLElement オブジェクト。HTMLElement.click() を呼んでいる 
            https://www.sejuku.net/blog/67735              
            ----------------------------------------------*/
            $('<a>', {
                href: window.URL.createObjectURL(new Blob([outputGPXstyle], {type : 'text/plain'})),
                download: fileName + '.gpx'
            })[0].click();  // ※ [0].click()*/
    } else {
        alert('There is no auth to export');
    }              
};

Upvotes: 0

Falke Design
Falke Design

Reputation: 11338

I created recently the small Leaflet Plugin L.ConvertCoords, which allows you to import (parse) and export (convert) layers in different Formats:

var gpxString = L.ConvertCoords.GPX.convert(layer);

In the back I use the library toGPX

Upvotes: 1

Related Questions