Kevin B
Kevin B

Reputation: 43

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

I'm working on a map where I'm creating GeoJSON layers asynchronously based on data from a JSON API. My initial data load works, and looking at the GeoJSON object, it appears to get the additional elements added.

However, if I then try to call map.getSource(...).setData(...) with the same source (the data element for which points to the updated GeoJSON object), I get

Error: TypeError: Cannot read property 'length' of undefined at Actor.receive (actor.js:77)

The only references I can find online are related to attempting to call setData on a style that no longer exists or has invalid GeoJSON data, but that doesn't seem to be the case—e.g.

> 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)

Any suggestions appreciated.

Upvotes: 2

Views: 8317

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126235

It looks like you're passing an array of features to setData() but you need to pass a valid GeoJSON object.

You should replace: map.getSource("advertisers").setData(features);

with:

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

Upvotes: 4

Related Questions