Search code examples
javascriptleafletgeojsonosrm

How to save geojson data from OSRM to a text file


I am using leaflet routine machine and mapbox to get routes. All works fine and I can console.log the route out but ideally I would like to save the geojson data to a text file so I can do testing without calling the API every time and I can change things too. I am using javascript with a browser, I can only see example in node.js, is this the only way?

Any ideas?


Solution

  • You can use FileSaver library to save files on the client-side

    // add the geojson to the map
    const geoJson = L.geoJson(freeBus).addTo(map);
    
    // use external library to save geojson
    const saveTxt = (content, filename) => {
      const file = filename + ".json";
      saveAs(new File([JSON.stringify(content)], file, {
          type: "text/plain;charset=utf-8"
        }), file);
    };
    
    // invoke the function by passing geojson to be saved
    // and .txt file name
    saveTxt(geoJson.toGeoJSON(), "test");
    

    Demo