Google Maps API V3 very slow when adding lots of Markers

google-maps-api-3, javascript

Solution

I don't use Markerclusterer but I make sure only the markers in the viewport are set on the map. for me this had significant boost in performance.

I used multiple arrays of markers that act as different layers. These layers are controlled by adding a marker.display attribute after creation wich I later play with. This way these will be ignored even if within the viewport.

Use the "idle" event: the "idle" will fire once the user has stopped panning/zooming, rather then "bounds_changed" event wich fires continuously when panning/zooming.

Add the event to the map in your window.onload function.

        google.maps.event.addListener(map, "idle", function (event) {
            if (map) {
                //This is the current user-viewable region of the map
                var bounds = map.getBounds();
                markerLayers.forEach(function (layer) {
                checkVisibleElements(layer, bounds);
                });
                checkVisibleElements(searchMarkers, bounds);
                //Loop through all the items that are available to be placed on the map
            }
        });


    function checkVisibleElements(elementsArray, bounds) {
        //checks if marker is within viewport and displays the marker accordingly - triggered by google.maps.event "idle" on the map Object
        elementsArray.forEach(function (item) {
            //If the item is within the the bounds of the viewport
            if (bounds.contains(item.position) && item.display == true) {
                //If the item isn't already being displayed
                if (item.map!=map){
                item.setMap(map);
                }
            } else {
                item.setMap(null);
            }
        });
    }

more info about the API(*) : Google Maps API : To Many Markers!

(*)original link dead, archived version from archive.org

Problem

I have many markers and markerclusterer I need to render on Google Map. I'm currently using the API (v3) and there are performance issues on slower machines. What should I do please?? I'm using ajax and XML

Original source