Hi,
I’m using Leaflet 1.7.1 in a Ionic4 component.
I’ve installed the plugin in this way:
npm install leaflet@latest --save
This is the code of the component:
export class PathmapComponent implements OnInit, OnDestroy {
...
pathMap: Leaflet.Map;
ngOnInit() {
// Init the map
this.leafletMap();
}
leafletMap() {
this.pathMap = Leaflet.map('pathMapId').setView([41.125426, 16.871062], 5);
Leaflet.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.pathMap);
}
This is the html of the component:
<ion-content class="map_container">
<div id="pathMapId" class="map_view"> </div>
</ion-content>
And this is the css of the component:
@import "~leaflet/dist/leaflet.css";
.map_container {
max-height: 200px;
border: 1px solid red;
}
.map_view {
height: 100%;
width: 100%;
overflow: hidden;
}
In the page that shows the component I can see the map, but it shows partially and it is not centered in the right coordinates:
Which could be the problem according to you?
cld
I think that the problem lies in the css file:
@import “~leaflet/dist/leaflet.css”;
I have tried to load it in the pathmap.component.css file and in the global.css file but the result is the same.
1 Like
you can set the map to invalidateSize after it’s loading
assuming you imported the leaflet.css correctly.
this.map.whenReady(() => {
setTimeout(() => {
this.map.invalidateSize();
}, 1000);
});
stackoverflow
1 Like
You need to initialize the map only after the ionic has completed animations
ionViewDidEnter() {
// init map directly or trigger onChange() inside separate component
}
1 Like
This solution works for me.
export class PODReportPage implements OnInit {
map!: L.Map;
constructor() { }
ngOnInit() {
this.initializeMap();
}
private initializeMap() {
this.map = L.map(‘map’).setView([24.466667, 54.366669], 13);
this.map.whenReady(() => {
setTimeout(() => {
this.map.invalidateSize();
}, 1000);
});
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
L.marker([24.466667, 54.366669]).addTo(this.map)
.bindPopup('A pretty CSS popup.<br> Easily customizable.')
.openPopup();
}
}