topojson 数据未在 openlayers 中呈现

topojson data not rendering in openlayers

我正在尝试将 topojson 文件加载到 openlayers

我使用来自 https://github.com/deldersveld/topojson/tree/master/continents

的 topojson 文件

当我画南美洲时它确实有效:

https://codepen.io/pixelatorz/pen/LdJwzQ?&editors=1010

var raster = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'https://api.tiles.mapbox.com/v3/mapbox.world-dark.json?secure'
  })
});

var style = new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)'
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1
  })
});

var vector = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://raw.githubusercontent.com/deldersveld/topojson/master/continents/south-america.json',
    format: new ol.format.TopoJSON(),
    overlaps: false
  }),
  style: style
});

var map = new ol.Map({
  layers: [raster, vector],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 1
  })
});

然而,当我将源 url 更改为北美或欧洲的源时,它不起作用,例如大洋洲就起作用了

示例: https://codepen.io/pixelatorz/pen/MVqqqJ?editors=1010

我测试了来自其他来源的一些其他 topojson 文件,有些确实可以绘制,有些则不会,我看不出文件之间有太大差异,也找不到问题所在。

您可以在代码笔中查看控制台时看到错误。当您使用 ol-debug.js 而不是生产版本时,调试起来会更容易:

VM1668 ol-debug.js:52808 Uncaught TypeError: geometryReader is not a function

at Function.ol.format.TopoJSON.readFeatureFromGeometry_ (VM52 ol-debug.js:52808)

错误背后的原因是,north-american 数据集包含没有类型的几何(也没有任何实际的几何数据)。

正如你在OL的TopoJson format source code, it tries to convert that to a geometry, using a list of geometryReaders中看到的那样。由于几何类型 null 没有 reader,因此失败。

但有一个简单的解决方法:为类型 null.

注册您自己的几何转换函数
ol.format.TopoJSON.GEOMETRY_READERS_[null] = function(object, scale, translate){
  // convert into dummy point
  return new ol.geom.Point([0,0]);
}