I'm using the HeatmapLayer api https://developers.google.com/maps/documentation/javascript/layers#JSHeatMaps
I generate the heatmap like this:
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapData,
radius: 50
});
heatmap.setMap(google_map);
When i want to display another heat map using the same function as above (i'm using ajax and i have new markers to display, so i need to change the heatmap too) the heat map layer stays on the map and in this case i have 2 overlapping heatmaps on my map. How can i remove the current heatmaplayer first?
Here is my demo code, if you click on the link below the map, the heatmap is added, of you click on it again, it should remove it, but its just duplicated over and over again:
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.