javascript - 如何访问加载在 html 文件中的 JSON 值?
问题描述
我正在尝试从我的 JSON 文件中获取坐标并将它们提供给 HTML 文件内的 Mapbox,而无需手动输入数据。我查看了一些帖子,发现有一个将 json 加载到我的 HTML 文件中。
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'C:\Users\ArkPr\yelp\restaurants.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}
loadJSON(function(json) {
var actual_JSON = JSON.parse(json);
这很好,但我不知道如何访问我想要的 JSON 文件中的值,即坐标。
{
"type": "featurecollections",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-0.153788,
51.513878
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-0.162122,
51.485349
]
}
},
// etc...
并让他们使用接下来的几行代码在地图上放置标记。
for (const { geometry, properties } of actual_JSON.features) {
// create a HTML element for each feature
const el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el).setLngLat(geometry.coordinates).addTo(map);
}
我缺少什么可以使这一切按预期工作?
解决方案
您可以使用像https://www.npoint.io/这样的在线模拟 JSON 服务器,代码如下:
$.getJSON("https://api.npoint.io/43c8857fb1f218a3b356", null, (actual_JSON)=>{
actual_JSON.features.forEach((feature)=> {
const el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el).setLngLat(feature.geometry.coordinates).addTo(map);
});
});
推荐阅读
- javascript - 开关盒内的for循环
- sql - oracle SQL left join() or full out join () exclude records based on keys
- r - Tidy method to split multiple columns using tidyr::separate
- scala - Can't compile example from book Advanced Scala with Cats
- c++ - 关于在 S-DES 中实现扩展器功能的更有效方法的简单问题
- android - 织物“crashlyticsUploadDistributionDebug”不存在
- javascript - running functions synchronously in firebase
- python - 如何使用 raspberry pi 和 python 扫描路由器的 RSSI 并根据值对它们进行排序?
- php - 检查两条路线(以纬度和经度表示)是否彼此相对
- angular - Angular 6 set 属性全局动态生成组件