Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic-Framework (4) - Openlayers map not working/visible

I tried to use Openlayers with Ionic but the map is not visible until a setTimeout..

Here is my working code:

import { Component, OnInit } from '@angular/core';

import OlMap from 'ol/map';
import OlOSM from 'ol/source/osm';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import OlProj from 'ol/proj';

@Component({
  selector: 'app-tab1',
  template: '<ion-content><div id="map" class="map"></div></ion-content>',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
  map: OlMap;
  ngOnInit() {
    const layer = new OlTileLayer({
      source: new OlOSM({ url: 'https://{a- b}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png' })
    });

    setTimeout(() => this.map = new OlMap({
      target: 'map',
      layers: [layer],
      view: new OlView({ zoom: 13, center: OlProj.fromLonLat([42, 10]) }),
      controls: []
    }), 0);
  }
}

app.module.ts:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

But if I don't use setTimeout, the map is not visible...

I have also tried to put the code in NgAfterViewInit but that is also not working.

It seems to be a dirty workaround using setTimeout for me. Does anyone have an idea why this problem or how to resolve it in a better way?

(I a similar behaviour with Angular and BrowserAnimationsModule the same behaviour. see here)

like image 873
stoph Avatar asked Aug 08 '26 20:08

stoph


1 Answers

Create a component using the answer I recently post in the one you mention

https://stackoverflow.com/a/54281422/2701198

then use the component in your page.

Hope it helps.

like image 123
cabesuon Avatar answered Aug 11 '26 10:08

cabesuon



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!