gpt4 book ai didi

javascript - 如何将 JSON 文档集合转换为 GeoJSON FeatureCollection

转载 作者:行者123 更新时间:2023-12-03 05:09:16 24 4
gpt4 key购买 nike

我有一个 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 要素集合的一部分,应如下所示(开头的额外类型信息和 {} 包装器):

{
"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"
}
}
]
}

我不确定是否有首选的转换方法、我缺少的技巧或某些在下载后重新格式化并添加额外数据的客户端代码,但我不确定最好的行动方案是什么添加额外的包装数据。

最佳答案

您可以创建自己的对象以获得所需的输出。这个例子可能对你有帮助。

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));

关于javascript - 如何将 JSON 文档集合转换为 GeoJSON FeatureCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41888652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com