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

Viewed 1878

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?

4 Answers

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

I did the following:

import { AfterViewInit, Component, OnInit } from '@angular/core';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, AfterViewInit {
  map!: Map;

  ngOnInit(): void {
    let view = new View({
      center: [0, 0],
      zoom: 1,
    });

    let layers = [
      new TileLayer({
        source: new OSM(),
      }),
    ];

    this.map = new Map({
      view: view,
      layers: layers,
      target: 'ol-map',
    });

    this.map.updateSize();
  }

  ngAfterViewInit(): void {
    this.map.updateSize();
  }
}

I think this is a clean way of solving this problem since in ngOnInit we define the map and we just update it's size once the view is initialized. Simple and effective.

I am updating window then it works

setTimeout(() => {
        oMap.updateSize();
    }, 0);
Related