我有一台服务器,其服务器具有标准json格式的地理数据,我需要将其更改为geojson格式,以便Mapbox可以读取它。你怎么做到的?
例如,您如何转换它:
[
{
"id": 0,
"name": "Hotel",
"icon": "Sleep",
"address": "SampleStreet 34",
"latitude": 12,
"longitude": 55
}
]
对此:
{
"type": "FeatureCollection",
"features": [
{
"id": 0,
"type": "Feature",
"properties": {
"placeID": 0,
"name": "Hotel",
"icon": "sleep",
"addressFormatted": "SampleStreet 34"
},
"geometry": {
"type": "Point",
"coordinates": [
12,
55
]
}
}
答案 0 :(得分:0)
有@turf库将对此提供帮助,因此您可以执行以下操作:
import { lineString as makeLineString } from '@turf/helpers';
然后使用它(请注意,经度优先)
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)
您应该在此处查看地图框示例:https://github.com/nitaliano/react-native-mapbox-gl/tree/master/example/src
答案 1 :(得分:0)
我使用了GeoJson(https://www.npmjs.com/package/geojson)来解析我的数据,看起来如下所示的效果很好:
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;
但是我现在想念的是我的feature.id。有人知道如何将其合并吗?我不希望我的ID位于属性下。
答案 2 :(得分:0)
如果您使用ES6,则类似的方法可能对您有用,如果您可以直接使用生成的对象,则可能不需要JSON.stringify
。
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));