Attention! Do you have any ideas for reorganizing and updating the Mapki? Please leave a note here. Thank you!

Reusing markers

From Google Mapki

Jump to: navigation, search

[edit] Reusing Markers

If you want to constantly update the position of a marker, for example marking a moving vehicle, you can leak vast amounts of memory if you keep removing the overlay and adding it back. It's possible to reposition a marker without leaking memory.

The Google code itself doesn't make it easy to identify the marker that you want to reuse, so the trick is to add your own identifier property to all your markers before calling addOverlay. When you want to update a marker at a later time you can scan through map.overlays[] to find the marker that has the required identifier.

Creating the marker, adding the property and adding the identifier looks like this

     marker = new GMarker(point);
     marker.id = 123;
     map.addOverlay(marker);

Scanning for a specific marker using the identifier, and updating it looks like this

     for (i =0; i<map.overlays.length; i++) {
       if (map.overlays[i].id) {
         if (map.overlays[i].id == index) {
           map.overlays[i].point.x = new_longitude;
           map.overlays[i].point.y = new_latitude;
           map.overlays[i].redraw(true);
         }
       }
     }

The first "if" is just there in case there are other markers or polylines for which no .id is set.

Avoid using local variables and things like "new GPoint()" in a function that updates the positions, because a fresh copy may get created each time.

This technique relies on the current internal structure of the Google data, rather than the documented interface, so it might need to be modified when the Google code changes.

Personal tools
Advertisement