Search code examples
javascriptgoogle-maps-api-3markerclusterer

when should Google Maps MarkerClusterer be called?


After feeding a bunch of points to a Google Map I realized I got way too many markers on my hand so I tried to use MarkerClusterer, with no success so far. As to my understanding, it should be called after the map is instantiated and populated - so I tried adding a markerCluster = new MarkerClusterer(map); just before return; Well, it doesn't work and I have no idea how could I move forward.

Also, in my example, init() is not called anywhere, but the map works. Does the instantiation happen at line #4? Most important, where do I go wrong?

function init() {
    var latlng = new google.maps.LatLng(map_center[0], map_center[1]);
    var myOptions = { zoom: 7, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, maxZoom: 18};
    map = new google.maps.Map(document.getElementById("map_div"), myOptions);

    for (var i = 0; i<addresses.length; i++) 
        {
            var pos = new google.maps.LatLng(
                    parseFloat(addresses[i]['lt']), 
                    parseFloat(addresses[i]['ln']) 
                );
            addMarker(pos, addresses[i]);   

        }

    return;
}

Solution

  • You need to pass an array of markers to the MarkerClusterer constructor. Here is your modified init function with very basic usage of MarkerClusterer:

    function init() {
      var latlng = new google.maps.LatLng(map_center[0], map_center[1]);
      var myOptions = { zoom: 7, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, maxZoom: 18};
      map = new google.maps.Map(document.getElementById("map_div"), myOptions);
      var markers = [];
    
      for (var i = 0; i<addresses.length; i++){
        var pos = new google.maps.LatLng(
          parseFloat(addresses[i]['lt']), 
          parseFloat(addresses[i]['ln']) 
        );
        markers.push(new google.maps.Marker({'position': pos}));
    
      }
    
      var markerCluster = new MarkerClusterer(map, markers);
    }