簡體   English   中英

如何將帶有對象的字典轉換為 geoJson?

[英]How do you convert a dictionary with objects into geoJson?

我們有一個帶有城市的字典,使用一個 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對象的每個值的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'] }); */

希望有幫助!

像這樣的事情應該有效。

const citiesArray = Object.values(cities);

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

根據 GeoJSON 規范,要包含具有緯度/經度坐標的idname屬性,您需要將對象解析為具有屬性features FeatureCollection類型。

每個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在線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM