Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openlayers map in Angular is blank when switching components

I have a MapComponent which loads an OpenLayers Map. This component is re-used in various of my Angular app's pages.

The map loads fine the first time. However, when I navigate to another component that contains the map, the map goes blank. In order to see it again, I have to navigate to a component that does not include the map, then navigate back to the desired page.

I only observe this behaviour since upgrading to Angular 10 (from 8).

Openlayers version 6.5 and 5.3 both exhibit this problem.

Attempts to solve:

  1. I've tried forcibly setting this.map = null in an OnDestroy lifecycle hook of my pages. Does not sound like a good solution and does not work.

  2. I've tried throwing an error in AfterContentInit:

ngAfterContentInit() {
   throw new Error("gramschaap");
}

It messes a bit with the rendering of the page and of course leaves a big fat error, but works.

  1. I've tried setting a timeout that removes and re-sets the target of the map in ngAfterViewInit:
ngAfterViewInit() {
    this.initMap();
    setTimeout(() => {
      if (this.map) {
        this.map.setTarget(null);
        this.map.setTarget("mapTarget");
      }
    }, 1000);
}

This of course means the map is blank for a second before it is redrawn; but it works!

  1. I've tried setting the map target to something non-existing at ngOnDestroy.
ngOnDestroy() {
    this.map.setTarget("raargitaar");  // does not exist
}

I thought it may have something to do with the target not initialising a second time. But it does not work.

like image 841
bluppfisk Avatar asked Aug 12 '26 13:08

bluppfisk


1 Answers

Another approach could be to use dynamic map ids as a target.

I eliminated my problem similar to your third attempt. However, I gave 0 timeout rather than giving 1 second and you don't need setTarget(null).

private initMap(): void {
  this.map = new Map({...})
  setTimeout(() => {
    this.map.setTarget('id');
  }, 0);
}
like image 159
Hawken Avatar answered Aug 14 '26 10:08

Hawken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!