2

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

4 Answers4

5

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);
cabesuon
  • 4,860
  • 2
  • 15
  • 24
1

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.

Beat Scherrer
  • 187
  • 2
  • 14
0

A bit more than a year ago I answer a similar question. Take a look at the question Angular 6 - Rendering problems if BrowserAnimationsModule imported (Openlayers) .

There you will find a couple of solutions, one uses OnInit method of the component plus ViewChild to get the reference element to bind the map. The other proposal uses AfterViewInit.

cabesuon
  • 4,860
  • 2
  • 15
  • 24
0

I am updating window then it works

setTimeout(() => {
        oMap.updateSize();
    }, 0);
Khurshid Ansari
  • 4,638
  • 2
  • 33
  • 52