如何解决将JSON转换为GeoJSON前端
我有一个来自开放数据API的json,我需要将其转换为geojson,以便可以将其显示为Mapbox地图上的图层。我正在使用Mapbox GL JS库:https://docs.mapbox.com/mapbox-gl-js/api/。这是打开数据json API的链接:https://data.cityofnewyork.us/resource/64uk-42ks.json。
我可以成功获取json api并将其打印到控制台,但是现在我需要将其转换为geojson。我知道我可以完全使用前端,因为它是开放数据。
这是我的代码:
var map = new mapboxgl.Map({
container: 'map',style: 'mapbox://styles/niki12step/ck8q9fgpx00d91ipipual7mrl',// replace this with your style URL
center: [-73.961581,40.683868],zoom: 9.5
})
var pluto_url = 'https://data.cityofnewyork.us/resource/64uk-42ks.json'
getData();
async function getData () {
await fetch(pluto_url)
.then(response => response.json())
.then(data => console.log(data))
}
解决方法
GeoJSON文件通常如下所示:
{
"type": "FeatureCollection","features": [
{
"type": "Feature","geometry": {
"type": "Point","coordinates": [75,25]
},"properties": {
"name": "earth"
}
}
]
}
“功能”是您所有功能的列表。每个要素都是一个对象,其键为“类型”,“几何”和“属性”,最后是“ id”。
这意味着您必须遍历JSON文件中的所有数据点并将其转换为这种格式。看起来可能像这样:
const pluto_url = 'https://data.cityofnewyork.us/resource/64uk-42ks.json';
getData();
async function getData () {
let mygeojson = {"type": "FeatureCollection","features": []}
await fetch(pluto_url)
.then(response => response.json())
.then(data => {
for(let point of data){
let coordinate = [parseFloat(point.longitude),parseFloat(point.latitude)];
let properties = point;
delete properties.longitude;
delete properties.latitude;
let feature = {"type": "Feature","geometry": {"type": "Point","coordinates": coordinate},"properties": properties}
mygeojson.features.push(feature);
}
});
console.log(mygeojson);
}
我假设您只有点几何。我使用parsedFloat()
是因为坐标是作为字符串存储在文件中的,但是GeoJSON格式需要浮点值。使用delete properties.longitude
和delete properties.latitude
,我实现了坐标不必要地成为属性字段的一部分。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。