带有动态源的 OLv5 矢量图层未渲染

OLv5 vector layer with dynamic source not rendering

我上周刚接触 OL,所以如果我遗漏了一些明显的东西,我深表歉意。它主要是从示例中拼凑而成,但我很确定我明白此时发生了什么。您可以在此处查看我的代码:https://fleur.github.io/dist/index.html, or more conventionally, here: https://github.com/fleur/olexample.

如果我创建一个带有矢量图层的地图,其源是静态文件(通过 'url' 属性),功能会按预期显示。如果我使用相同的代码创建地图,其中唯一的区别是源是进行 xhr 调用的加载程序函数,则不会显示这些功能。

在这两种情况下,我都在源和层上放置了监听器,并触发了这些事件:

静态:

precompose
postcompose
addfeature
addfeature
addfeature
change
precompose
render
postcompose

动态:

precompose
postcompose
addfeature
addfeature
addfeature
change
precompose
postcompose

请注意,动态事件序列中没有 'render' 事件。我什至进行同步 HTTP 调用。我完全不知所措。动态源加载器函数对闭包做了一些棘手的事情,所以也许这与它有关?不过,该代码取自 openlayers.org 上的示例,并且仅使用 console.log 和不同的 url.

进行了修改

所以,我的问题是:我怎样才能获得动态检索的功能,这些功能会添加到源中并进行渲染?

当使用 URL 使用 GeoJSON、GPX、KML 或 OSMXML 格式的数据时,OpenLayers 库会自动进行从 EPSG:4326 到 EPSG:3857 的再投影,而当您进行手动 Ajax call,做这个转换是你的责任。渲染不会发生,因为您的要素超出了绘制它们的范围。

要解决您的问题,

const f = dynamic_source.getFormat().readFeatures(xhr.responseText);

添加

// Return at the moment geometry with longitude-latitude / WGS 84 / EPSG:4326
// like [-122.3563599, 37.5793804]
// Only here for learning purpose, you can remove it after understanding my point
console.log(f[0].getGeometry().getCoordinates());

// Reproject coordinates manually by mutating the current geometry in place
f.forEach(feature => feature.getGeometry().transform('EPSG:4326', 'EPSG:3857'));

PS:已测试