[英]Openlayers map tiles are not initially loaded in single page app
我有一個使用構建的單頁應用程序
地圖容器已加載,並具有帶有ol-
的子元素以及左上角的縮放控件。 這樣 Openlayers 腳本就成功執行了。 但它不會在加載時顯示地圖圖塊。
當我調整瀏覽器的大小時,地圖圖塊突然出現。 所以我想知道:
在瀏覽器調整大小時觸發瓷磚突然渲染的事件是什么,我如何自己觸發它以便地圖在加載時正確顯示?
我的index.pug
看起來像這樣:
doctype html
html(lang='de')
head
meta(charset='UTF-8')
meta(http-equiv='X-UA-Compatible', content='ie=edge')
meta(
name='viewport'
content='width=device-width, initial-scale=1')
title=`myTitle`
// Stylesheets
link(
rel='stylesheet',
href='https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css')
link(
rel='stylesheet',
href='/assets/style.css')
// Scripts
script(src='https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js')
script(src='https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList')
script(src='https://code.jquery.com/jquery-3.3.1.min.js')
script(data-main='/js/main', src='/js/require.js')
body
include header
include tabs
main
#loader Loading...
include map
include footer
在main
部分中,您會看到包含的map
哈巴狗模板,如下所示:
section.component#component-map
#map.map
script.
/**
* Leaflet Map
*/
// Create markers and geodata
const mapCenter = [13.429, 52.494];
const siteData = !{JSON.stringify(sites)};
const features = siteData.map(site => {
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ Number(site.longitude), Number(site.latitude) ]
}
}
});
const image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: "red", width: 1})
});
const styles = {
"Point": new ol.style.Style({
"image": image
})
}
const styleFunction = function(feature) {
return styles[feature.getGeometry().getType()];
};
const geojsonObject = {
"type": "FeatureCollection",
"features": features
};
const vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
const map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.fromLonLat(mapCenter),
zoom: 17,
})
});
自己找到答案。 我的“解決方案”比實際解決方案更多是一種解決方法。 我等待地圖腳本執行(當地圖容器具有子類名為ol-viewport
的子元素時就是這種情況),然后手動觸發瀏覽器resize
事件。 除了我的預期之外, map.render()
或map.renderSync()
方法不會加載圖塊。 因此,解決方法如下所示:
const waitForMap = setInterval(function() {
if ($('.ol-viewport').length) {
console.log("Exists!");
window.dispatchEvent(new Event('resize'));
clearInterval(waitForMap);
}
}, 100);
有點難看,但這個解決方案救了我。 我沒有使用 jQuery,所以將 .length() 替換為:
const waitForMap = setInterval(function() {
const e = document.querySelector(".ol-viewport");
const cr = e.getClientRects();
if ((cr.length != 0) && (cr[0].width != 0) && (cr[0].height != 0)) {
console.log("Render OpenLayer map");
window.dispatchEvent(new Event('resize'));
clearInterval(waitForMap);
}
}, 500);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.