javascript - 使用 Mapbox GL JS 单击关闭标记层时如何关闭弹出窗口
问题描述
当单击关闭标记层时,我无法关闭/删除弹出窗口。我曾尝试在 onclick 函数中使用 popup.remove,但没有太多运气将该函数与用于显示和隐藏标记层的按钮绑定。非常感谢关闭或隐藏标记层时关闭弹出窗口的任何帮助。
JS:
// add popup to layer
map.on('click', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ["high_camp"] // Add layers
});
if (!features.length) {
return;
}
var feature = features[0];
var popup = new mapboxgl.Popup({
offset: {
'top': [0, 0],
'top-left': [0, 0],
'top-right': [0, 0],
'bottom': [0, -40],
'bottom-left': [0, -40],
'bottom-right': [0, -40],
'left': [18, -22],
'right': [-18, -22],
}
})
.setLngLat(feature.geometry.coordinates)
.setHTML(feature.properties.NAME)
// Change attribute, properties.'Replace' (Uppercase)
.addTo(map);
});
// Toggle high camp layer
var togglehighcampId = ["high_camp"]; // Add layer
document.getElementById("highcampIcon").onclick = function (e) {
// Change button name, getElementById('Replace')
for (var index in togglehighcampId) {
var clickedLayer = togglehighcampId[index];
e.preventDefault();
e.stopPropagation();
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
if (visibility === 'none') {
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
this.className = '';
} else {
this.className = 'on';
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
}
}
};
解决方案
也许您可以将弹出窗口保持在全局范围内,以便在 onclick 方法中访问它
像这样的东西:
var popup;
// add popup to layer
map.on('click', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ["high_camp"] // Add layers
});
if (!features.length) {
return;
}
var feature = features[0];
popup = new mapboxgl.Popup({
offset: {
'top': [0, 0],
'top-left': [0, 0],
'top-right': [0, 0],
'bottom': [0, -40],
'bottom-left': [0, -40],
'bottom-right': [0, -40],
'left': [18, -22],
'right': [-18, -22],
}
})
.setLngLat(feature.geometry.coordinates)
.setHTML(feature.properties.NAME)
// Change attribute, properties.'Replace' (Uppercase)
.addTo(map);
});
// Toggle high camp layer
var togglehighcampId = ["high_camp"]; // Add layer
document.getElementById("highcampIcon").onclick = function (e) {
// Change button name, getElementById('Replace')
for (var index in togglehighcampId) {
var clickedLayer = togglehighcampId[index];
e.preventDefault();
e.stopPropagation();
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
if (visibility === 'none') {
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
this.className = '';
} else {
this.className = 'on';
popup.remove(); // REMOVE THE POPUP WHEN THE LAYER IS REMOVED
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
}
}
};
PS:代码未经测试
推荐阅读
- c# - IValueConverter 作为对象返回而不是预期的值
- php - 来自变量的 PHP 正则表达式匹配
- java - 文件夹包含点 (.) 时的编译器错误
- lua - 通过使用本地函数优化 Lua 代码
- dart - 如何将映射中的数组转换为字符串数组
- jupyter-notebook - 如何在 Jupyter Notebook 中启用令牌身份验证?
- java - 无静态方法元工厂(OptaPlanner)
- python - 使用 Pandas 在位置上拆分字符串
- python - Pandas 部分删除重复值
- android - java.lang.IllegalStateException:键 f0 的片段不再存在:唯一 id