Pavan Kusunuri
Pavan Kusunuri

Reputation: 387

Leaflet JS: Cannot read property 'addLayer' of undefined while rendering drawnItems on Map

I tried to display the leaflet Map on which It contains polygon-shaped surfaces on it. Sometimes it is displaying the error cannot read property 'addLayer' of undefined when the page is refreshed map is rendering properly. I don't know where I did wrong Please guide me

componentDidUpdate(prevProps, prevState) {
    const { user, surfaces } = this.props;
    const { allLayers } = this.state;
    const that = this;
    let selectedSurface = null;

   if (!prevProps.user.id && user.id) {
     this.initializeMap();
   }


  if (allLayers.length === 1 && surfaces.length > 1) {
    let allLayers = [{ key: -1, name: this.props.intl.formatMessage({ id: 
      'surface.allsurfaces' }), color: '#CCCCCC' }];
    surfaces.forEach((o) => {
     let l = new L.geoJSON(o.geometry)._layers;
     [l] = Object.keys(l).map(ob => l[ob]);
     const customlayer = this.addPopupToLayer(o, l);
     drawnItems[o.surface_type.id].addLayer(customlayer);
     l.on('click', (e) => {
       if (selectedSurface) {
         selectedSurface.editing.disable();
       }
       selectedSurface = e.target;
       e.target.editing.enable();

       that.setState({
         popup: true,
         detail: true,
         surfaceDetail: o,
         typeSelected: o.surface_type,
         editSurface: selectedSurface
       });
     });

     allLayers.push({
       key: o.surface_type.id,
       name: o.surface_type.name,
       color: o.surface_type.color
      });
    });
    allLayers = allLayers.filter(
     (l, index, self) => self.findIndex(
       t => t.key === l.key
     ) === index
    );
    this.setState({
     allLayers,
     counter: surfaces.length
    });
  }
}

Upvotes: 1

Views: 1397

Answers (1)

Pavan Kusunuri
Pavan Kusunuri

Reputation: 387

After debugging the problem about why it causing the issue for refresh i.e map not getting the props values while drawItems.So, I wrote a condition that after getting prop values I tried to addLayer.Now it is working fine. Hope it helps someone

Upvotes: 1

Related Questions