问题
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?
回答1:
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
.
回答2:
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);
来源:https://stackoverflow.com/questions/60775376/i-cant-display-the-openlayer-map-properly-until-after-a-window-resize