async-await - 传单映射:分配对象以获取本地 GeoJSON 文件的承诺
问题描述
我希望从本地 GeoJSON 文件中分配一个 Fetch API 承诺作为对象。这是代码
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites
}).addTo(map);
});
};
我尝试了回调方法,如此处所建议的将 获取的 JSON 保存到变量中
(编辑)新代码,但仍然缺少形式参数
function getData("data/sites.geojson", cb) {
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function (feature, layer) {
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
.then(function(result) {
cb(result);
});
});
};
getData("data/sites.geojson", function (data) {
return console.log({data});
});
解决方案
我找到了解决这个问题的方法,方法是在 fetch 函数中添加我最初想在地图上做的事情。
这是L.controlLayer
使用 geojson 作为覆盖添加一个。
这是使它工作的代码:
let sites = getData()
.then((function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function LayerControl(feature, layer) {
var popupText = "<b>" + feature.properties.nombre + "<br>";
layer.bindPopup(popupText);
category = feature.properties.tipo;
// Initialize the category array if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = L.layerGroup().addTo(map);
layersControl.addOverlay(categories[category], category);
}
categories[category].addLayer(layer);
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
}));
实际上,它来自您在另一篇文章ghybs上的回答之一。
推荐阅读
- wordpress - 如何构建自定义插件以与当前主题集成
- angular - 处理大型数据集时无法在 mat-paginator 中设置初始 pageIndex
- python - 如何解决“拒绝执行‘常量’语句”错误?
- html - CSS div float:left 问题,列有不同的高度
- jquery - 选择选项上的 J-query 输入字段未隐藏
- javascript - 在文本输入控件中,如何用退格替换删除,反之亦然?
- c# - 本地游戏对象变量无法使用 switch 方法(Unity)
- mongodb - 从不同容器连接时出现 MongoNetworkError
- python - 当存在重复项时,如何将两个元素列表转换为字典(一个元素是键,另一个是值)?
- angular - 调试单元测试时,Typescript 代码启用了覆盖率