javascript - 如何在 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();
}
解决方案
加载数据需要一些时间(即使是这个较短的 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>
推荐阅读
- android - 访问mysql时无法补偿时差
- java - 无法移除 Camel Quartz 路线
- javascript - 在 DOM 中呈现表格后,AngularJS 将带有链接的单元格链接到表格中
- sql - 仅使用 select 语句模拟表
- reactjs - 无法解析 '@material-ui\core\Box' 中的 '@material-ui/styles/styled'
- java - 从项目和变量替换生成 Maven 原型
- asp.net-core-mvc - ASP.NET Core MVC 2.2 进程内托管 - 请求中止 CancellationToken 不起作用
- vba - 查找/替换 OLE 链接的问题
- python - 有没有办法将装饰器的返回值传递给函数 args?
- r - 您如何将 R devtools::install_git 与 TFS 托管的 Git Repo 一起使用?