【问题标题】:How do you convert a dictionary with objects into geoJson?如何将带有对象的字典转换为 geoJson?
【发布时间】:2020-05-10 10:16:04
【问题描述】:

我们有一个包含城市的字典,使用 uniqe id 作为键:

cities: {
    'adfjlx9w': {
      name: 'New York',
      latitude: 4,
      longitude: -7
    },
    'favkljsl9': {
      name: 'Copenhagen',
      latitude: 2,
      longitude: -18
    }
  }

我们需要将字典转换为 Geojson 以便将城市放置在地图上,但不能使用下面的典型路线,因为它不是对象数组:

GeoJSON.parse(cities, {
      Point: ['latitude', 'longitude']
    });

最快最好的方法是什么?

【问题讨论】:

  • 也许可以试试cities.keys().map()

标签: javascript dictionary object geojson


【解决方案1】:

如果我理解正确,您需要将cities 对象的每个值的latitudelongitude 数据提取到形状的纬度/经度值数组中:

{ latitude, longitude }

一种方法是使用Object#values,它返回一个包含cities 值的数组,并且可选地使用Array#map 将每个对象转换为一个新对象(只有纬度、经度值):

const cities = {
    'adfjlx9w': {
      name: 'New York',
      latitude: 4,
      longitude: -7
    },
    'favkljsl9': {
      name: 'Copenhagen',
      latitude: 2,
      longitude: -18
    }
  }  

const latlngArray = Object
// Extract value array from cities
.values(cities) 
// Map each value to lat/lng only object
.map(item => ({ latitude : item.latitude, longitude : item.longitude })) 

console.log(latlngArray);

/* Pass latlngArray to GeoJSON.parse
GeoJSON.parse(latlngArray, {
  Point: ['latitude', 'longitude']
});
*/

希望有帮助!

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作。

    const citiesArray = Object.values(cities);
    
    GeoJSON.parse(citiesArray, {
          Point: ['latitude', 'longitude']
        });
    

    【讨论】:

      【解决方案3】:

      根据 GeoJSON 规范,要包含带有纬度/经度坐标的 idname 属性,您需要将对象解析为类型为 FeatureCollection 并带有属性 features

      每个features 数组对象应该是Feature 类型,具有propertiesgeometry 值。 properties 值应包含元数据,geometry 值应为 Point 类型,coordinates 属性包含纬度/经度。

      const cities = {
        'adfjlx9w': {
          name: 'New York',
          latitude: 4,
          longitude: -7
        },
        'favkljsl9': {
          name: 'Copenhagen',
          latitude: 2,
          longitude: -18
        }
      }
      
      let citiesGeoJSON = Object.entries(cities)
        .reduce((
          _cities,
          [cityID, cityData],
        ) => {
          let city = {
            "type": "Feature",
            "properties": {
              "id": cityID,
              "name": cityData.name,
            },
            "geometry": {
              "type": 'Point',
              "coordinates": [
                cityData.latitude,
                cityData.longitude,
              ],
            },
          }
          _cities.features.push(city)
          return _cities
        }, {
          "type": "FeatureCollection",
          "features": [],
        })
      

      网上有个GeoJSON Linter

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-27
        • 2018-02-11
        • 2016-05-19
        • 2015-11-05
        • 2018-07-15
        • 1970-01-01
        • 2019-10-10
        相关资源
        最近更新 更多