rakete
rakete

Reputation: 3051

LeafletJS not loading all tiles until moving map

I am trying to load a simple leaflet map in my Ionic 2 app. Unfortunately not all tiles are loaded currectly until a moving the map.

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
    });

enter image description here

Upvotes: 13

Views: 14114

Answers (3)

mbauer
mbauer

Reputation: 344

Just put the creation of the map into the Ionic ionViewDidEnter lifecycle method. Much cleaner than any 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);
}

Upvotes: 2

HamidReza
HamidReza

Reputation: 1934

this work for me fine :

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);

Upvotes: 3

Maihan Nijat
Maihan Nijat

Reputation: 9355

There are a couple of solutions for this problem:

1- Add "./node_modules/leaflet/dist/leaflet.css" in the styles array in `angular.json'.

2- Invalidate size when a map is ready:

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

Add this to your template:

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

And this will bind onMapReady method which you have in your component.

3- Install Leaflet typings for Typescript:

npm install --save-dev @types/leaflet

Vanilla JavaScript:

1- Validate the size of map:

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

2- Add leaflet stylesheet leaflet/dist/leaflet.css in the <head> of your document.

Upvotes: 14

Related Questions