Call map.getSource(...).setData(...) results in TypeError: Cannot read property 'length' of undefined

Call map.getSource(...).setData(...) results in TypeError: Cannot read property 'length' of undefined

我正在制作一张地图,其中我根据来自 JSON API 的数据异步创建 GeoJSON 图层。我的初始数据加载有效,并且查看 GeoJSON 对象,它似乎添加了额外的元素。

但是,如果我随后尝试使用相同的源(指向更新后的 GeoJSON 的数据元素)调用 map.getSource(...).setData(...)对象),我得到

错误:TypeError:无法读取未定义的 属性 'length' 在 Actor.receive (actor.js:77)

我在网上能找到的唯一参考文献是关于尝试在不再存在或具有无效 GeoJSON 数据的样式上调用 setData,但事实似乎并非如此——例如

> map.getSource("advertisers");
e {id: "advertisers", type: "geojson", minzoom: 0, maxzoom: 18, tileSize: 512, …}
> features;
(7634) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
> features[0];
{type: "Feature", geometry: {…}, properties: {…}} 
> features[0].geometry;
{type: "Point", coordinates: Array(2)}
> map.getSource("advertisers").setData(features);
e {id: "advertisers", type: "geojson", minzoom: 0, maxzoom: 18, tileSize: 512, …}
evented.js:111 Error: TypeError: Cannot read property 'length' of undefined
at Actor.receive (actor.js:77)

感谢任何建议。

您似乎正在将一组要素传递给 setData(),但您需要传递一个有效的 GeoJSON 对象。

你应该替换:map.getSource("advertisers").setData(features);

与:

map.getSource("advertisers").setData({
  type: 'FeatureCollection',
  features: features
});