Remove HeatmapLayer from Google Maps

I am using the HeatmapLayer api https://developers.google.com/maps/documentation/javascript/layers#JSHeatMaps

I generate a heatmap as follows:

heatmap = new google.maps.visualization.HeatmapLayer({ data: heatmapData, radius: 50 }); heatmap.setMap(google_map); 

When I want to display a different heat map using the same function as above (I use ajax, and I have new markers for display, so I need to change the heat map as well) the heat map layer remains on the map, in which case I have two overlapping heat maps on my map. How can I remove the current thermoplastic first?

Here is my demo code, if you click on the link below the map, a hot map is added, you click on it again, it should delete it, but it just repeats it again and again:

http://jsfiddle.net/LpL3P/

+6
source share
4 answers

Documents suggest removing the layer by calling heatmap.setMap(null)

Update

In your jsfiddle, you declare 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 the new heatmap did not overwrite the existing one.

Here is your updated jsfiddle

+8
source

For anyone else looking for a solution a few years after the initial post, I found the following. Start by declaring the variable as global, which will contain the MVCbject heat map.

 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 }); 
+3
source

Take a look at the google JSHeatMaps documentation here.

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

 heatmap.setMap(null) 
+1
source

Using heatmap.setMap(null) will only hide your heat map layer. If you later type heatmap.setMap(map) , you will again see your heat map layer, so you really didn’t delete it.

To delete data, you need to do the following:

heatmap.setMap(null) // This will hide the heat map layer

heatmap.getData().j = []; // This is what actually sets the array of coordinates to zero.

heatmap.setMap(map) // Now, when you switch back the map, the heater does not work, and you can create a new one.

Hope this helps. Spent me figure it out, but it definitely worked.

+1
source

All Articles