问题
I have a server with geographic data in normal json format, which I need to change into geojson format so Mapbox can read it. How do you do this?
For example, how do you convert this:
[
{
"id": 0,
"name": "Hotel",
"icon": "Sleep",
"address": "SampleStreet 34",
"latitude": 12,
"longitude": 55
}
]
into this:
{
"type": "FeatureCollection",
"features": [
{
"id": 0,
"type": "Feature",
"properties": {
"placeID": 0,
"name": "Hotel",
"icon": "sleep",
"addressFormatted": "SampleStreet 34"
},
"geometry": {
"type": "Point",
"coordinates": [
12,
55
]
}
}
回答1:
There are @turf libraries that will help with this, so you could do something like:
import { lineString as makeLineString } from '@turf/helpers';
and then use it like (note that longitude goes first)
var coords = [];
var dataarray = JSON.parse(thejson);
for (var i=0; i < dataarray.length; i++){
obj = dataarray[i];
coords.push([obj.long, obj.latitude]);
}
let mapboxpoints = makeLineString(coords)
You should check out the mapbox examples here: https://github.com/nitaliano/react-native-mapbox-gl/tree/master/example/src
回答2:
I used GeoJson (https://www.npmjs.com/package/geojson) to parse my data, and it looks like the following which works quite well:
import GeoJSON from 'geojson';
import jsonData from './jsonData.json';
const json = jsonData;
const data = GeoJSON.parse(json, {
Point: ['latitude', 'longitude'],
include: ['name', 'icon', 'addressFormatted']
});
export default data;
What I'm missing now however, is my feature.id. Does anyone know how to incorporate that in? I do not want my id to be under properties.
回答3:
If you use ES6 then something like this might work for you, JSON.stringify
might not be needed if you can use the resulting object directly.
const data = [
{
id: "0",
name: "Hotel",
icon: "Sleep",
address: "SampleStreet 34",
latitude: "12",
longitude: "55"
},
{
id: "1",
name: "Landmark",
icon: "Star",
address: "SampleStreet 1234",
latitude: "99",
longitude: "100"
}
];
const geojson = {
type: "FeatureCollection",
features: data.map(item => {
return {
id: item.id,
type: "Feature",
properties: {
placeID: item.id,
name: item.name,
icon: item.icon,
addressFormatted: item.address
},
geometry: {
type: "Point",
coordinates: [item.latitude, item.longitude]
}
};
})
};
console.log(geojson);
console.log(JSON.stringify(geojson));
来源:https://stackoverflow.com/questions/55496909/how-do-you-convert-normal-geographic-json-coming-from-server-into-geojson