Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove HeatmapLayer from google maps

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/

like image 375
passatgt Avatar asked Dec 31 '12 17:12

passatgt


People also ask

How do you remove a heatmap?

As heatmaps are only created when clicking View heatmap for a particular URL and not stored on the Heatmaps page, there is no deletion option needed. If you've saved a heatmap to the sidebar, you can delete it by clicking on the vertical ellipsis menu next to the heatmap name and then clicking Remove.

Is heat a map?

A heat map is a two-dimensional representation of data in which values are represented by colors. A simple heat map provides an immediate visual summary of information. More elaborate heat maps allow the viewer to understand complex data sets.


2 Answers

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);
}
like image 67
Marko Rochevski Avatar answered Nov 03 '22 02:11

Marko Rochevski


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
});
like image 41
Professor Abronsius Avatar answered Nov 03 '22 02:11

Professor Abronsius