我有一个RESTapi,它从mongoDB中提取数据,并使用以下代码将其作为JSON数组传递给我的mapbox gl应用程序:
$.ajax(
{
type: "GET",
contentType: "application/json; charset=utf-8",
url: myUrl,
cache: false,
async: true,
timeout: 5000,
dataType: "json",
success: function (data)
{
console.log("Reading Data");
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError)
{
console.log("http Status Response: " + xhr.status);
console.log(thrownError);
}
});
数据作为单独的文档存储在mongo中,get以下列格式提取。
[
{
"_id": "588a3d5a524da321dd937891",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.5299938027191, 53.42859997065679 ]
},
"type": "Feature",
"properties": {
"icon": "horse-riding-15",
"title": "A Horse",
"description": "A Horse description",
"date": "2017-01-26T18:18:02.175Z"
}
},
{
"_id": "588ac68aa99e6a38134997b5",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.56076949999999, 53.4528447 ]
},
"type": "Feature",
"properties": {
"icon": "dog-park-15",
"title": "A Dog",
"description": "A Dog description",
"date": "2017-01-27T04:03:22.381Z"
}
}
]
要在mapbox中读取它,它必须是GeoJSON Feature Collection的一部分,它应该如下所示(开头的额外类型信息和{}包装器):
{
"type": "FeatureCollection",
"features": [
{
"_id": "588a3d5a524da321dd937891",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.5299938027191, 53.42859997065679 ]
},
"type": "Feature",
"properties": {
"icon": "horse-riding-15",
"title": "A Horse",
"description": "A Horse description",
"date": "2017-01-26T18:18:02.175Z"
}
},
{
"_id": "588ac68aa99e6a38134997b5",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.56076949999999, 53.4528447 ]
},
"type": "Feature",
"properties": {
"icon": "dog-park-15",
"title": "A Dog",
"description": "A Dog description",
"date": "2017-01-27T04:03:22.381Z"
}
}
]
}
我不确定是否有首选的转换方法,我缺少的技巧,或者某些客户端代码在下载后重新格式化并添加额外数据,但我不知道。我不确定添加额外包装数据的最佳方法是什么。
答案 0 :(得分:1)
您可以创建自己的对象以获得所需的输出。这个例子可能会帮助你。
var dataReturned = [
{
"_id": "588a3d5a524da321dd937891",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.5299938027191, 53.42859997065679 ]
},
"type": "Feature",
"properties": {
"icon": "horse-riding-15",
"title": "A Horse",
"description": "A Horse description",
"date": "2017-01-26T18:18:02.175Z"
}
},
{
"_id": "588ac68aa99e6a38134997b5",
"__v": 0,
"geometry": {
"type": "Point",
"coordinates": [ -113.56076949999999, 53.4528447 ]
},
"type": "Feature",
"properties": {
"icon": "dog-park-15",
"title": "A Dog",
"description": "A Dog description",
"date": "2017-01-27T04:03:22.381Z"
}
}
];
var geoJSON = {};
geoJSON["type"] = "FeatureCollection";
geoJSON["features"] = dataReturned;
console.log(JSON.stringify(geoJSON));