首页 > 解决方案 > 如何在 Javascript 中导出 GeoJSON

问题描述

我创建了一个 GeoJSON 列表,并试图通过网页中的按钮将其导出到文件中。除了导出的文件只显示“未定义”并且没有任何 GeoJSON 数据外,一切正常。我究竟做错了什么?

HTML

  <button onclick="exportToJsonFile()">Download GeoJSON</button>

脚本

 var api = $.getJSON("https://api.data.gov.sg/v1/environment/rainfall?date=2019-07-03",
   function rainfall(data_rainfall){
   apiGeo = { type: "FeatureCollection", features: []};
             //---- apiGeo is populated here ----//

  console.log(apiGeo);     //displays data in GeoJSON format in browser console
});

function exportToJsonFile(apiGeo) {
let dataStr = JSON.stringify(apiGeo);
let dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);

let exportFileDefaultName = 'data.json';

let linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
} 

标签: javascriptjsonexportgeojson

解决方案


加载数据需要一些时间(即使是这个较短的 json 版本,加载后按钮名称也会更改为 full)。但即使在片段中也有效。问题是未使用的函数参数,然后是未加载数据时。

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()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="exportToJsonFile()">Download</button>


推荐阅读