问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/54105934/ionic-framework-4-openlayers-map-not-working-visible