Remove HeatmapLayer from google maps

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

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/

回答1:

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



回答2:

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


回答3:

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) 


回答4:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!