How to export GeoJSON in Javascript

后端 未结 1 2011
粉色の甜心
粉色の甜心 2021-01-07 05:06

I have created a GeoJSON list and am trying to export it to file via a button in the webpage. Everything works fine except that the file that is exported only displays \'und

1条回答
  •  隐瞒了意图╮
    2021-01-07 05:25

    Takes some time to load data (even this shorter json version, button name is changed to full after load). But works even in snippet. Problem was unused function parameter and then when data was not loaded.

    function loadData() {
      var api = $.getJSON("https://api.data.gov.sg/v1/environment/rainfall",
        function rainfall(data_rainfall) {
          apiGeo = { type: "FeatureCollection", features: [], input: api.responseJSON };
          //---- apiGeo is populated here ----//
    
          console.log(apiGeo);     //displays data in GeoJSON format in browser console
          document.body.getElementsByTagName("BUTTON")[0].innerText += " GeoJSON";
        });
    }
    function exportToJsonFile() {
      downloadObjectAsJson(apiGeo, "data");
    }
    function downloadObjectAsJson(exportObj, exportName) {
      if (navigator.msSaveBlob) { // IE10+
        var blob = new Blob([JSON.stringify(exportObj)], {type : 'application/json'});
        return navigator.msSaveBlob(blob, exportName + ".json");
      }
      var dataStr = "data:application/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
      var downloadAnchorNode = document.createElement('a');
      downloadAnchorNode.setAttribute("href", dataStr);
      downloadAnchorNode.setAttribute("download", exportName + ".json");
      downloadAnchorNode.innerText = exportName;
      document.body.appendChild(downloadAnchorNode); // required for firefox
      downloadAnchorNode.click();
      downloadAnchorNode.remove();
    }
    loadData()
    
    

    0 讨论(0)
提交回复
热议问题