We have a dictionary with cities, using a uniqe id as the key:
cities: {
'adfjlx9w': {
name: 'New York',
latitude: 4,
longitude: -7
},
'favkljsl9': {
name: 'Copenhagen',
latitude: 2,
longitude: -18
}
}
We need to convert our dictionary into Geojson in order to place the cities on a map, but cannot use the typical route below, as it is not an array of objects:
GeoJSON.parse(cities, {
Point: ['latitude', 'longitude']
});
What is the fastest and best way to do this?
If I understand correctly, you need to extract the latitude
and longitude
data for each value of the cities
object to an array of latitude/longitude values of shape:
{ latitude, longitude }
One approach would be to use Object#values
which returns an array of the values for cities
, and, optional use Array#map
to transform each object to a new object (with only the latitude, longitude values):
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'] }); */
Hope that helps!
Something like this should work.
const citiesArray = Object.values(cities);
GeoJSON.parse(citiesArray, {
Point: ['latitude', 'longitude']
});
According to the GeoJSON Specification, to include the id
and name
properties with latitude/longitude coordinates, you would need to parse the object as type FeatureCollection
with a property features
.
Each features
array object should be of type Feature
, with properties
and geometry
values. The properties
value should contain the metadata, and the geometry
value should be of type Point
with coordinates
property containing latitude/longitude.
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": [],
})
There is a GeoJSON Linter online.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.