Remove HeatmapLayer from google maps
You need to declare the heatmap
globally and then when you want to display new data on the heatmap do this:
let heatmap;
setData(heatmapData) {
if (heatmap) {
// Clear heatmap data
heatmap.setMap(null);
heatmap.setData([]);
}
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapData
});
heatmap.setMap(this.map);
}
The docs suggest you can remove a layer by calling heatmap.setMap(null)
Update
In your jsfiddle you were declaring your heatmap
variable in the scope of each click
event. To make your code work I moved the heatmap
variable to exist globally, and then checked to make sure that a new heatmap
did not overwrite an existing one.
Here is your updated jsfiddle
Using heatmap.setMap(null)
will only hide your heatmap layer.
If you later type heatmap.setMap(map)
, you will see your heatmap layer again, so it didn't really get deleted.
In order to delete the data you have to do the following steps.
heatmap.setMap(null)
//This will hide the heatmap layer
heatmap.getData().j = [];
//This is what actually sets the coordinates array to zero.
heatmap.setMap(map)
//Now when you toggle back the map, the heatlayer is gone and you can create a new one.
Hope this helps. Took me a while to figure it out, but it definitely worked.
For anyone else searching for a solution years after the original post I found the following worked. Begin by declaring the variable as a global that will hold the heatmap MVCObject.
var mvcObj;
Then, in the function you use to add the heatmap
if( typeof( mvcObj )=='object' ) mvcObj.clear();
/* locations is an array of latlngs */
mvcObj = new google.maps.MVCArray( locations );
/* this.map is a reference to the map object */
var heatmap = new google.maps.visualization.HeatmapLayer({
data: mvcObj,
map: this.map
});