Nik*_*iki 2 json geojson mapbox-gl-js
我有来自开放数据 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))
}
Run Code Online (Sandbox Code Playgroud)
GeoJSON 文件通常如下所示:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [75, 25]
},
"properties": {
"name": "earth"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
“功能”是所有功能的列表。每个特征都是一个带有“type”、“geometry”和“properties”键以及最终“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);
}
Run Code Online (Sandbox Code Playgroud)
我假设你只有点几何形状。我之所以使用它parsedFloat(),是因为坐标在文件中以字符串形式存储,但 GeoJSON 格式需要浮点值。delete properties.longitude我发现delete properties.latitude坐标并不是属性字段中不必要的一部分。
| 归档时间: |
|
| 查看次数: |
2860 次 |
| 最近记录: |