javascript - Leaflet map not updating view
问题描述
I'm trying to display a map in a modal, so when I close it and open a new one, the map shows always the first location instead of the current modal. I reset the map, but still nothing happens.
Before open the modal, I print the map:
$('#openMap').on($.modal.BEFORE_OPEN, function(event, modal) {
printMap('map', coord);
});
After closing modal, I remove the map container:
$('#openMap').on($.modal.AFTER_CLOSE, function(event, modal) {
$('#map').remove();
});
This is printMap function code:
var map = null; // Global variable
function printMap(map_id, coord) {
const mapbox_token = '...';
if(map) {
map.eachLayer(function (layer) {
map.removeLayer(layer);
});
map.off();
map.remove();
map.on('viewreset', function (e) {
console.log('Reset view...') // Do not showed
})
delete map;
map = null;
// none of these work
}
// Load map
map = L.map(map_id).setView(coord, 13);
// Create the tile layer with correct attribution
L.tileLayer(...).addTo(map);
// Add marker
L.marker(coord).addTo(map);
// Invalidate size for modal
$('.modal').on($.modal.OPEN, function (event, modal) {
setTimeout(function(){ map.invalidateSize()}, 0);
});
}
Hope somebody could help me! Thanks in advance!
解决方案
Your map
variable is local to your printMap
function, i.e. whenever you execute that function, it gets a new allocation for its local variable. Hence map
is always uninitialized when you check it.
Then you may have a scoping issue for your coords
value when you use it to attach your modal before open listener.
推荐阅读
- c++ - reinterpret_cast 可以更改对象表示吗?
- java - 如果正在显示 AlertDialog,则停止其余的 UI 元素事件
- macos - 尝试连接时的 SSH 问题
- php - Vue.js / Laravel - 正确处理注销
- php - 当我从 mysql、PHP GD 中提取图像时,横幅会出现奇怪的颜色
- c - C在头文件中定义一个指向外部函数的宏函数
- java - 转发:在课堂上找不到 mblogBegginer 的设置器/字段
- php - Github 没有运行 PHP
- android - NativeScript Vue Android 动态壁纸
- matlab - 寻找高斯分布的交点