【发布时间】:2020-06-26 22:57:59
【问题描述】:
我有一些我想在传单地图中使用的 json 数据。我需要将 json 格式转换为传单使用的 geojson 格式。我还想将数据分类为朋友和家人,以便在地图上分别识别它们。
我已成功获取(编辑)数据文件并使用切换语句将数据分类为朋友案例和家庭案例。在每种情况下,我都会将数据转换为 geojson 格式。
我的问题是我无法弄清楚如何在函数 getData 之外使用变量 myFriends 和 myFamily 以便我可以在地图上绘制点。
这只是我用来学习如何使用传单的虚假数据。最终我希望通过一个流来获取这些数据,以跟踪到时刻的位置数据。
在我的代码中,我可以通过在函数内移动console.log(myFriends); 将数据输出到控制台。
我想要获得 2 个变量 myFriends 和 myFamily,每个变量都包含所有迭代数据。
原始 JSON 数据
[
{
"time" : 0.00,
"ID" : 51,
"name" : "John",
"relationship" : "Friend",
"Lat" : 56.166609,
"Long" : 27.157364
},
{
"time" : 0.00,
"ID" : 52,
"name" : "Sally",
"relationship" : "Friend",
"Lat" : 55.895501,
"Long" : 26.753631
},
{
"time" : 0.00,
"ID" : 50,
"name" : "Tom",
"relationship" : "Family",
"Lat" : 56.236112,
"Long" : 26.168675
}
]
var myFriends =
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
56.166609, 27.157364
]
},
"type": "Feature",
"properties": {
"popupContent": "John"
},
"id": 51
},
{
"geometry": {
"type": "Point",
"coordinates": [
55.895501, 26.753631
]
},
"type": "Feature",
"properties": {
"popupContent": "Sally"
},
"id": 52
},
]
};
var myFamily =
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"popupContent": "Tom"
},
"geometry": {
"type": "Point",
"coordinates": [56.236112, 26.168675]
}
},
]
};
程序代码
async function getData() {
const response = await fetch('data.json');
var data = await response.json();
//console.log(data);
for (var i = 0; i < data.length; i++){
var unit = data[i];
var relationship = unit.relationship;
switch (relationship) {
case "Friends":
var myFriends = {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
unit.Lat + " , " + unit.Long
]
},
"type": "Feature",
"properties": {
"popupContent": unit.name
},
"id": unit.ID
},
]
};
break;
case "Family":
console.log("Family");
console.log(unit);
}
}
}
getData();
console.log(myFriends);
【问题讨论】:
标签: javascript json leaflet geojson