9
votes

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:

http://jsfiddle.net/LpL3P/

5

5 Answers

12
votes

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

5
votes

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
});
2
votes

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.

2
votes

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);
}
1
votes

Take a look at the documentation here google JSHeatMaps.

Check out this example. You can view the logic for the toggle button.

heatmap.setMap(null)