GMaps: clearOverlays bugged

2007-12-25

Well, that's another two days lost. Great. Google Maps as a beautifull API. The API contains a function of the map called clearOverlays() that should remove all the overlays from the map.The function obviously works to a certain extend. All the overlays are visually removed. However, when you start to work with events you're eventually bound to run into the invisible problem I'm addressing here. The problem is probably even a memory leak...Case: Take any map. Draw a couple of lines and GEvent.addListener attach a click-event to them. Add a property to the GPolyline object with a unique id (for example, use Math.random()) and echo it in the click-event using an alert().So now you have a map with lines and when you click on the lines you get a unique number for each line. Try to remember one or use simpeler id's.Now remove all the overlays using the .clearOverlays() function and redraw the (same) lines but give these lines different id's. Make sure to create new GPolyline objects. Click again on a line. You'll notice the id's have not changed (tested in FF/O/IE).This problem took me a long time to resolve because I was chasing the wrong bug. I thought I was dealing with a closure problem. That was the only thing I could imagine because I'm working with anonymous functions and I was unsure how local variables were passed onto the functions. This page actually exactly described my problem I thought I had. My doubts were correct since I had it all wrong. Unfortunately that did not solve my current problem.The real problem lies in the clearOverlays() function. This function, removing all overlays from the map, does not remove the events attached to these overlays. Perhaps this is by design, but the removeOverlay() function DOES remove events. So if it is design, the design is incosistent (and undocumented!). Another couple of hours of my life I'll never get back. Great.So when using overlays in google maps and replacing these overlays, make sure the events are removed as well! Specifically use removeOverlay() calls or by clearOverlays and specific removeListener() calls.