Saturday, 14 September 2019

Mapbox JS: Efficient and simple way to change a property of a feature

I am trying to change the property (value) of a feature (based upon id) in a layer. I cannot use setFeatureState, because I need to cluster the features based on the value property and clusterProperties does not support feature-state aggregation. The current way I'm using to set the value property of a feature with a specific id is the following (every 2 seconds, I iterate through every feature in the GeoJSON and set the property):

setTimeout(() => {
  const newGeojson = {
    ...geojson,
    features: geojson.features.map(feature => {
      if ([0, 1].includes(feature.id)) { // update features selectively
        feature.properties.value= 1;
      }
      return feature;
    })
  };
  map.getSource('geom').setData(newGeojson);
}, 2000);

This is terribly inefficient with a time complexity of O(nk), with k being the number of features I want to change—I have around 130,000 features. In fact, it causes my browser to crash. I tried using mapbox-gl-js's MapboxDraw (mapbox-gl-js has a setFeaturePropertymethod), but it takes too long to load the 130,000 features (crashing the browser), so that didn't work as an option. Is there a more feasible option where I can set the property of a feature at runtime without it taking forever?

My GeoJSON (geojson variable) is of the following format (Mapbox requires GeoJSON data):

{ 
    "type":"FeatureCollection",
    "features":[ 
        { 
            "type":"Feature",
            "id":0,
            "geometry":{ 
                "type":"Point",
                "coordinates":[ 
                    1.49129,
                    42.46372
                ]
            },
            "properties":{ 
                "country":"AD",
                "city":"Sant Julià de Lòria-0",
                "value":0
            }
        },
        { 
            "type":"Feature",
            "id":1,
            "geometry":{ 
                "type":"Point",
                "coordinates":[ 
                    1.73361,
                    42.54277
                ]
            },
            "properties":{ 
                "country":"AD",
                "city":"Pas de la Casa-1",
                "value":0
            }
        }
    ]
}



from Mapbox JS: Efficient and simple way to change a property of a feature

No comments:

Post a Comment