Remove HeatmapLayer from google maps

前端 未结 5 1307
余生分开走
余生分开走 2021-01-17 18:09

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

I generate the heatmap like this:

heatm         


        
相关标签:
5条回答
  • 2021-01-17 18:28

    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)
    
    0 讨论(0)
  • 2021-01-17 18:40

    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
    });
    
    0 讨论(0)
  • 2021-01-17 18:42

    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

    0 讨论(0)
  • 2021-01-17 18:48

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 18:54

    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.

    0 讨论(0)
提交回复
热议问题