Search code examples
angulartypescriptionic-frameworkopenlayers

I can't display the openlayer map properly until after a window resize


I set up the map like this:

this.map = new Map({
  target: 'map',
  layers: [new TileLayer({source: new OSM()})
  ],
  view: new View({
    center: [0, 0],
    zoom: 16,
  })
});

On opening the page I get this:

before resizing

So I open the console to make the page smaller and the map is loaded:

after resizing

Do you have any idea how to fix it?


Solution

  • I solved the problem for me. It was actually a timing issue. The solution is the following: I inserted an ng-if on the html element. and set the target of the map after a one-second time-out.

    html:

    <ion-item *ngIf="loaded">
      <div id="map" [ngClass]="{'map': loaded}"></div>
    </ion-item>
    

    .ts:

    this.map = new Map({
      view: new View({
        center: [0, 0],
        zoom: 16,
        minZoom: 2,
        maxZoom: 19
      }),
      layers: [
        new TileLayer({
          source: new OSM()
        }),
      ]
    });
    this.loaded = true;
    setTimeout(() => {
      this.map.setTarget(document.getElementById('map'));
    }, 1000);