javascript - javascript将json数据迭代到geojson中以获取传单
问题描述
我有一些我想在传单地图中使用的 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);
解决方案
您的 var myFriends的范围仅限于函数 getData()。要在 getData() 之外访问它,您需要在最后返回它。
推荐阅读
- kubernetes - 使用 Workload Identity 将 GCP Cloud SQL 数据库导出到存储桶
- php - Composer 在服务器中检测到问题
- sql - 计算每天从 iphone 和 web 登录的唯一用户数
- c# - 在 HttpClient 中设置标头以授权 rest api
- c# - 如何在 Prism 中不打开 MainWindow 的情况下创建模块目录和 Reigster 类型
- python - Pandas:agg() 给我的“系列”对象是可变的,因此它们不能被散列
- android - 完成后获取多个网络请求的结果
- python - 有没有办法加快在 python 中处理大型 CSV 和数据帧?
- php - Office365 smtp 并不总是与 php 邮件程序一起使用
- node.js - Typescript 编译的 JS 可以工作,但 ts-node-dev 抛出编译错误