[英]How do you convert normal geographic json coming from server into 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
對象的每個值的latitude
和longitude
數據提取到形狀的緯度/經度值數組:
{ 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 規范,要包含具有緯度/經度坐標的id
和name
屬性,您需要將對象解析為具有屬性features
FeatureCollection
類型。
每個features
數組對象都應該是Feature
類型,具有properties
和geometry
值。 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.