将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.longitudedelete properties.latitude,我实现了坐标不必要地成为属性字段的一部分。