【问题标题】:How to convert JSON to GeoJson JavaScript如何将 JSON 转换为 GeoJson JavaScript
【发布时间】:2021-09-03 23:43:55
【问题描述】:

我从数据库中获得了一个 JSON,但现在我需要将其转换为 GeoJson 以在我的地图中使用它

我找到了这个解决方案,但它显示了一个未定义的数组。

$.getJSON("./origin/neworigin.json", function(jsonData) {
    var outGeoJson = {}
    outGeoJson['properties'] = jsonData
    outGeoJson['type']= "Feature"
    outGeoJson['geometry']= {"type": "Point", "coordinates":
        [jsonData['latitude'], jsonData['longitude']]}
  
    console.log(outGeoJson)
  });

这是来自 myJSON 的示例

[{"station":"BORJA","institution":"SENCICO","longitude":"-77.0064","latitude":"-12.0855"},
    {"station":"SCARQ","institution":"SENCICO","longitude":"-71.5408","latitude":"-16.385"},
    {"station":"SCAR2","institution":"SENCICO","longitude":"-71.5364","latitude":"-16.3934"},...

in browser

【问题讨论】:

    标签: javascript json maps geojson


    【解决方案1】:

    检查数组是否为空。

    尝试更改变量名称。

    提供更多细节。

    【讨论】:

      【解决方案2】:

      您有两个选项来创建有效的 GeoJSON 表单 JSON。

      1. 创建 GeoJSON.Point 数组和 GeoJSON.FeatureCollection
      2. 创建 GeoJSON.MultiPoint 对象 以下是代码 sn-ps:

      const jsonData = [{
          "station": "BORJA",
          "institution": "SENCICO",
          "longitude": "-77.0064",
          "latitude": "-12.0855"
        },
        {
          "station": "SCARQ",
          "institution": "SENCICO",
          "longitude": "-71.5408",
          "latitude": "-16.385"
        },
        {
          "station": "SCAR2",
          "institution": "SENCICO",
          "longitude": "-71.5364",
          "latitude": "-16.3934"
        }
      ];
      
      
      // to GeoJSON.Point array
      const geoJSONPointArr = jsonData.map(row => {
        return {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [row.longitude, row.latitude]
          },
          "properties": row
        }
      });
      
      console.log(geoJSONPointArr);
      
      // to GeoJSON.FeatureCollection
      const pointArrFeatureCollection = {
        "type": "FeatureCollection",
        "features": geoJSONPointArr
      }
      
      console.log(pointArrFeatureCollection);
      
      // to GeoJSON.MultiPoint
      const geoJSONMultiPoint = {
          "type": "Feature",
          "geometry": {
            "type": "MultiPoint",
            "coordinates": jsonData.map(row => [row.longitude, row.latitude])
          },
          "properties": {
            originalData: jsonData
          }
        }
      
      console.log(geoJSONMultiPoint);

      我还推荐使用 turf 库,它在使用 GeoJSON 格式时非常方便。

      【讨论】:

        猜你喜欢
        • 2011-08-02
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 2021-05-22
        • 2014-11-25
        • 2018-03-16
        • 2019-03-06
        • 1970-01-01
        相关资源
        最近更新 更多