Search code examples
javascriptgoogle-maps-api-3memory-leakslagoverlays

Google Maps V3 custom function: togglePolygons() Extreme lag after a few toggles


I have some pretty large polygons (the xml file I use to generate them is 400k and is just point data).

Once the user loads the polygons by clicking a button I store those polygons in an array.

var schoolDistPolygon = new google.maps.Polygon({
      paths: points,
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 3,
      fillColor:color,
      fillOpacity: 0.35
    });
    schoolPolygons.push(schoolDistPolygon);

I then use this method toggle the polygons on on and off:

function toggleOverlays (the_array, mode){
   var arr = eval(the_array);
   if(mode=='hide'){
    for(i=0;i<arr.length;i++)
    {
        arr[i].setMap(null);

    }
         $("#schoolDistButton").bind('click',function(){toggleOverlays(the_array,'show')});
    }

       if(mode=='show'){
    for(i=0;i<arr.length;i++)
    {
        arr[i].setMap(map);

    }
         $("#schoolDistButton").bind('click',function(){toggleOverlays(the_array,'hide')});
    }


}

I've also tried just saving and setting the polygons edge and fill opacity to 0 instead of out right removing them but i get the exact same lag.

After the toggle button is clicked a few times there is extreme lag. and the browser crashes. This happens in chrome, firefox, ie, opera...all browsers I could get my hands on.


Solution

  • You bind the click-event on every function-call, but previously bound clicks still exist.

    First unbind the click:

    $("#schoolDistButton").unbind('click')