Leaflet map not showed properly

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

I’ve solved using this library: GitHub - Asymmetrik/ngx-leaflet: Core Leaflet package for Angular.io

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

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