使用最新版本的Openlayers,4.3.1
,我设置了一个矢量源如下:
this.vectorSource = new ol.source.Vector({
url: `../assets/data/file.json`,
format: new ol.format.TopoJSON()
});
this.vector = new ol.layer.Vector({
source: this.vectorSource,
style: this.style
});
但在某些情况下,文件需要通过其他功能进行预先处理。
我如何加载 file.json
,处理他并在 ol.source.vector
中使用?
我也尝试使用 ajax 响应,其中 dataSource
变量是第一个示例 ../assets/data 中对相同
URL
的 ajax 调用的响应/文件.json
vectorSource = new ol.source.Vector({
features: (new ol.format.TopoJSON()).readFeatures(dataSource)
});
最佳答案
这可以很容易地完成。在没有 URL 的情况下配置 ol.source.Vector
。相反,您可以自己加载 json 并将其转换为对象
var json = JSON.parse(dataSource);
然后修改JSON对象,最后调用
var features = new ol.format.TopoJSON().readFeatures(dataSource,
{featureProjection: view.getProjection()});
vectorSource.addFeatures(features);
请注意 featureProjection
选项,这是必需的,除非您的 View 与数据源具有相同的投影。
关于javascript - 如何在没有 XHR 的情况下加载 vectorSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988289/