codebot
codebot

Reputation: 717

Edit a geojson source in mapbox and re-render layer

I have a geojson layer for extruding polygons in mapbox . A filter that at the beginning shows nothing.

  map.current.addSource('congeoex', {
    type: 'geojson',   
      data: 'http://localhost:3000/geometries.geojson' 
  }); 

  map.current.addLayer({
    'id': 'congeoex',
    'type': 'fill-extrusion',
    'source': 'congeoex',
    'paint': { 
      'fill-extrusion-color': 'black', 
      'fill-extrusion-height': ['+',['to-number', ['get', 'mytop']] , 7],   
      'fill-extrusion-base':  ['+',['to-number', ['get', 'mytop']], 5]  
    },
    //show nothing at first
    'filter': ['==', ['get','no'], 0]
  }); 

Then I dynamically get an array of no properties, representing features to be somehow extruded.

After I get the array, I change the filter of the layer . Then I want to edit the geojson source of the layer, based on that array and add a custom attribute to the geojson that is the increasing elevation of the extrution. That custom attribute must be named mytop, to be the same found in 'fill-extrusion-height fill-extrusion-base.

map.current.setFilter('congeoex', ['in',['get', 'no'] , ['literal',array_of_no]] )   
const geojsonSource = map.current.getSource('congeoex'); 
console.log('geojsonSource ', geojsonSource);
//edit geojson to add mytop attribute
//map.current.triggerRepaint();

I cannot actually do that because the map.current.getSource('congeoex'); does not give back the actual geojson data of the layer to be edited.

I tried getting the geojson data and editing, but looks like it changes the data on the front-end locally, not the data in mapbox, because I see no change on the map

fetch('http://localhost:3000/geometries.geojson')
.then((res)=>{ 
  const data = res.json()  
  return data
})
.then(a => { 
  
  let anew = a.features.filter(item => array_of_no.includes(item.properties.no));

  let elevHeight = 10;
  anew.forEach(e =>{ 
    e.properties.customTop = elevHeight; 
    elevHeight = elevHeight + 10;
  }); 

})

map.current.setFilter('congeoex', ['in',['get', 'no'] , ['literal',array_of_no]] )   
map.current.triggerRepaint();

So, how can I edit the geojson source of a mapbox layer, change layer filter and then re-render the map ?

Thank you

Upvotes: 0

Views: 465

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126907

You're so close.

  1. Fetch the GeoJSON file.
  2. Manipulate it however you want.
  3. Call map.getSource('congeoex').setData(...)

Upvotes: 1

Related Questions