本文介绍了如何在Javascript中导出GeoJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个GeoJSON列表,并试图通过网页中的一个按钮将其导出到文件中.除导出的文件仅显示未定义"且不显示任何GeoJSON数据外,其他一切工作正常.我在做什么错了?
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 'undefined' and none of the GeoJSON data. What am I doing wrong?
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版本,在加载后按钮名称也将变为完整).但是即使在摘要中也可以使用.问题是未使用的功能参数,然后是当未加载数据时.
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()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="exportToJsonFile()">Download</button>
这篇关于如何在Javascript中导出GeoJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!