LeafletJS在移动地图时无法加载所有瓦片

13

我正试图在我的Ionic 2应用程序中加载一个简单的leaflet地图。不幸的是,在移动地图之前并没有全部加载正确的瓦片。

this.map = new L.Map('mainmap', {
      zoomControl: false,
      center: new L.LatLng(40.731253, -73.996139),
      zoom: 12,
      minZoom: 4,
      maxZoom: 19,
      layers: [this.mapService.baseMaps.OpenStreetMap],
      attributionControl: false
    });

输入图像描述


4
可能您正处于这种情况下:https://dev59.com/oloV5IYBdhLWcg3wc-Ym#36257493 - ghybs
3个回答

13

针对这个问题有几种解决方案:

1-在`angular.json'中的样式数组中添加"./node_modules/leaflet/dist/leaflet.css"

2-在地图准备就绪时使大小无效:

onMapReady(map: L.Map) {
    setTimeout(() => {
      map.invalidateSize();
    }, 0);
}

将此添加到您的模板中:

<div style="height: 300px;"
   leaflet
   (leafletMapReady)="onMapReady($event)">
</div>

这将绑定您组件中的 onMapReady 方法。

3- 为 TypeScript 安装 Leaflet 类型:

npm install --save-dev @types/leaflet

纯 JavaScript:

1- 验证地图的大小:

onMapReady(map: L.Map) {
   setTimeout(() => {
     map.invalidateSize();
   }, 0);
}

2- 在文档的 <head> 中添加 leaflet 样式表 leaflet/dist/leaflet.css


1
看起来你假设了一些Leaflet Angular包装器,而OP使用原生JS初始化他们的Leaflet地图。 - ghybs
@ghybs 感谢你的提示。我编辑了答案,不过解决方案几乎相同,只是实现方式有所不同。 - Maihan Nijat
2016年的确是这样,Angular 2可能没有提供angular.json文件。但我认为你也应该修改监听器部分:如果OP不使用Angular包装器,他们就没有leafletMapReady事件。我宁愿看ViewChild和组件生命周期。 - ghybs
嗨,我添加了这个但是它给了我错误信息:无法读取未定义的属性'_leaflet_pos',你有任何想法吗? - akshay kishore
它必须被包装在setTimeout中。我不知道为什么,但这是我让它工作的唯一方法。 - Dirk Schumacher
显示剩余2条评论

3
这对我很有效:
this.map = L.map('map');
const self = this;
    
this.map.on("load",function() { setTimeout(() => {
   self.map.invalidateSize();
}, 1); });
    
this.map.setView([36.3573539, 59.487427], 13);

它必须被包装在setTimeout中。我不知道为什么,但这是我让它工作的唯一方法。 - Dirk Schumacher

2

将地图的创建放入Ionic的ionViewDidEnter生命周期方法中。比任何setTimeout hack都更加简洁 ;)

import { Map, tileLayer } from 'leaflet';

...

ionViewDidEnter(): void {
    this.map = new Map('map', {
       center: [48.1351, 11.5819],
       zoom: 3
    });

   const tiles = tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
       maxZoom: 18,
       minZoom: 3,
       attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OSM</a>'
   });

   tiles.addTo(this.map);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接