googlearchive / js-marker-clusterer

A marker clustering library for the Google Maps JavaScript API v3.
https://googlemaps.github.io/js-marker-clusterer/docs/reference.html
Apache License 2.0
1.28k stars 775 forks source link

markers which have identical coordinates don't collapse #102

Open lolaswift opened 7 years ago

lolaswift commented 7 years ago

Markers which have identical coordinates get nicely clustered by markerclusterer. However, when clicked, the cluster gets zoomed in but it doesn't collapse and show individual markers.

Raffone17 commented 7 years ago

After line 1053:


google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_, event); 

add:


var zoom = this.map_.getZoom();
  var maxZoom = markerClusterer.getMaxZoom();
  // if we have reached the maxZoom and there is more than 1 marker in this cluster
  // use our onClick method to popup a list of options
  if (zoom >= maxZoom && this.cluster_.markers_.length > 1) {
     return markerClusterer.onClickZoom(this.cluster_);
  }

then in yuor application, after created a MarkerClusterer object add something similiar:

markerCluster.onClickZoom = function(cluster) { 
    var markers = cluster.markers_ ;
    //your function here
    // in cluster.markers_ you can found the array of the markers of the cluster
 };

If you're having trouble with the max zoom, set like this in your markerCluster object

markerCluster.setMaxZoom(21);
lolaswift commented 7 years ago

@Raffone17, Thank you very much for the help Rafael! Do you think https://github.com/jawj/OverlappingMarkerSpiderfier is a better solution? -lola

brianshim commented 7 years ago

I came up with another solution, which is to add a bit of "noise" to the coordinates so that they don't lie on top of each other. This won't work if you have a large number of overlapping pins, and it adds a tiny bit of inaccuracy to the pin locations, but it will un-overlap pins if the "noise" pattern is crafted properly.

Basically, I use a count variable that increments for every pin. Using that count, I generate a repeating noise pattern using mod inside my loop:

noise_lat = ((count%5)/10000) - .00002; noise_long = ((count%3)/10000) - .00001;

Then I add this to the latitude and longitude:

var latitude = parseFloat(real_latitude) + noise_lat; var longitude = parseFloat(real_longitude + noise_long);

You can then use those coordinates for your marker parameters.

Like I said, it introduces a tiny bit of error in the pin locations. It's usually less than 1 city block, which is fine for my application. It won't work if you have a large number of overlapping pins, but you can tweak the noise pattern to deal with that. If you have pins that are very close together, this algorithm could cause them to overlap if you're unlucky. So, this isn't for life-or-death applications, but for me, it solved the problem the vast majority of the time.

Best, Brian