Cannot remove heat layer on leaflet map

Viewed 14

I am trying to build an application that uses leaflet, PostgreSQL and PHP. I have created the APIs in PHP and added some layers from PostgreSQL and it works fine. The main theme of the app is to allow the user to be able to filter the points using some fields(its working fine) and I am also trying to show a heatmap that also gets filtered based on the form. I used this heatmap.js (https://github.com/Leaflet/Leaflet.heat) addon for leaflet. Initially all the data loads on my webpage and I am able to add the heat layer too using this code below:

geoJson2heat = function(geojson, weight) {
  

return geojson.features.map(function(feature) {
        return [parseFloat(feature.geometry.coordinates[1]), 
                parseFloat(feature.geometry.coordinates[0]), 
                parseFloat((feature.properties[weight]))];
      });
    }
 var geoData = geoJson2heat(lyr, 'area_cos');
    
 var myconf = {
      minOpacity: 0.7,
      radius: 25,
      blur: 25,
      max: 1300
    };
    
 var heat = L.heatLayer(geoData, myconf).addTo(map);
 layerControl.addOverlay(heat, 'Heat Map');

This displays the heatmap perfectly fine. Now I also have a form that allows user to take inputs and filter the data based on that. So when a user submits the form, it gets the filtered data from postgresql and displays it. When I try to apply the same concept to this heat layer, it does not work. I am not able to remove the layer, rather it shows me an error. This is the code I am trying to use:

$('#filterForm').submit(function(e){
  e.preventDefault()
  map.removeLayer(heat);
  
  layerControl.removeLayer(heat);

.
. rest of the code here working fine
.
});

I get this error:

Uncaught TypeError: Cannot read properties of undefined (reading '_leaflet_id')

I try to print some properties of the heat layer to see if its displaying or not to make sure my layer is correct in the code but get the same error (even thought the layer is perfectly visible on the map and works fine). But if I try to print the properties of this layer outside of this jquery form submit listener, it works and shows me the correct information. I suspect that it has something to do with me calling the remove layer in the jquery listener specifically for the heat layer (because I removed other layers, point layer within this jquery listener and its working fine). I was hoping if you could tell me what the issue is and help me get a work around of this. I am just a beginner, so stuck in here.

Thanks!

0 Answers
Related