Skip to main content

Working through an app project I inherited using Ionic, Angular and ngx-leaflet to name a few elements... I had a problem where the map shows only all map tiles when navigating via my app in the Xcode simulator.  The simulator screen would show just a small tile and the rest of the area where the map should be visible stays in gray color.

Image
leaflet map original position wrong tiles showing

 

Versions

plugin / component version
@capacitor/cli 3.4.3
leaflet 1.8.0
@asymmetrik/ngx-leaflet 8.1.0
@angular/core 13.3.4
@ionic-native/core 5.36.0

 

Files

Taking snippets of the key areas of the following files

map-detail.page.html

    <ion-spinner name="lines" *ngIf="!mapLoaded"></ion-spinner>
      <ion-card *ngIf="mapLoaded">
        <div id="map"
          leaflet
          [leafletOptions]="mapOptions"
          [leafletLayers]="layers"
          (leafletMapReady)="onMapReady($event)"
          style="height: 300px"
        ></div>
      </ion-card>

map-detail.page.ts:

/**
   * Determine the Map structure
   */
  setupMap() {
    const tiles = tileLayer(
      "https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png",
      {
        maxZoom: 18,
        attribution: "..."
      }
    );

    this.mapOptions = {
      center: latLng(-25.734968, 134.489563),
      zoom: 3,
      layers: [tiles],
      zoomControl: false,
      scrollWheelZoom: false
    };
  }

  onMapReady(map: Map) {
    this.map = map;
  }

 

After a lot of trial and error and Googling.... I was able to find out that map.invalidateSize() has a part to play in the solution.  But the question how?

Through reading 'Data-toggle tab does not download Leaflet map' it needs to be attached to the map object.  Which in this instance needs to be in the onMapReady function.

However, when I tried the following


  onMapReady(map: Map) {
    map.invalidateSize();
    this.map = map;
  }

No impact.

In turn, maybe the issue was time base, so I applied a timeout

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

Reload and working

Image
leaflet map correct position on load

Related articles

Andrew Fletcher31 Oct 2023
Android icon not changing
If the Android app icon is not changing from the default icon (in my situation this was the Capacitor icon), here are some steps to troubleshoot and resolve the issue:&nbsp;Check the Icon FilesEnsure that you have provided the correct icon files in the appropriate directory. In a Capacitor project,...
Andrew Fletcher29 Sep 2023
Setting up an ionic app
Recently a client handed me code that runs an app through iOS and Android. &nbsp;No details about whether native or otherwise. &nbsp;Once I had the opportunity to crawl through the code, definitely not native. &nbsp;Typescript, Angular, Cordova... etc.Glancing at the modification dates, the last...