针对这个问题有几种解决方案:
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
。
angular.json
文件。但我认为你也应该修改监听器部分:如果OP不使用Angular包装器,他们就没有leafletMapReady
事件。我宁愿看ViewChild和组件生命周期。 - ghybsthis.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);
将地图的创建放入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: '© <a href="http://www.openstreetmap.org/copyright">OSM</a>'
});
tiles.addTo(this.map);
}