Peacefull
Peacefull

Reputation: 566

Correct way to use MarkerClusterer with $.ajax call

I want to use the library "MarkerClusterer" (Google page) to cluster my markers on Google Maps via the API.

I tried to implement it to my actual code that seams to work but when I zoom out/in the cluster disapear. And when i refresh the page the clusters numbers are not the same. Why ?

Here is what i want to do with this API :

enter image description here

jsfiddle : my code

$.ajaxq (qyName, {
        url: url,
        dataType: 'json'
    }).done(function( data ) {
                var address = getParameterByName('address', this.url);
                var index = errorArray.indexOf(address);
                try{
                    var p = data.results[0].geometry.location;
                    var latlng = new google.maps.LatLng(p.lat, p.lng);

                    marker = new google.maps.Marker({
                        position: latlng,
                        map: map
                    });

        // Add markers to array
        map.markers.push(marker);

        markerCluster = new MarkerClusterer(map, map.markers, {
            imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
        });

});

What i'm doing wrong ? Thx for the help.

Upvotes: 0

Views: 680

Answers (1)

Peacefull
Peacefull

Reputation: 566

Well i answer to my question because i found the solution thanks to @Lixus for puting me in the right way !

We must set the new MarkerClusterer outside the ajax call and set it with an empty array for markers. Then we call the method .addMarkers() with our markers array.

var mcOptions    = {gridSize: 50, maxZoom: 15, imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'};
var mc           = new MarkerClusterer(map, [], mcOptions);

Then in our ajax call we do something like that :

 marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: icon,
            // Custom property to hold the filters options, it'a used below to filter the markers
          });

          // Add markers to array
          map.markers.push(marker);

          mc.addMarkers(map.markers);

Working jsfiddle

Upvotes: 2

Related Questions