Leaflet / Leaflet.markercluster

Marker Clustering plugin for Leaflet
MIT License
3.94k stars 996 forks source link

map.flyto zoom level that marker is no longer in cluster. #954

Open 7ammer opened 5 years ago

7ammer commented 5 years ago

This is a feature request. I've only just found this plugin but I have had a look around and can't find the feature. Sorry if it already exists.

.flyto(latLng, zoomLevel) currently zooms to a predefined zoom level zoomLevel. It would be great if I could find the zoom level of marker where it is no longer in a cluster so I can enter that into the .flyto(latLng, zoomLevel) function.

Thanks for your time :)

waseemyusuf commented 5 years ago

@7ammer You can use the .zoomToShowLayer() method to do this. Remember that this is a method of the markerClusterGroup object and NOT the map object. For more info, refer to the documentation under 'Other Group Methods'. You can also read my answer to a simliar question on StackOverflow. Note that this function pans to your marker, and does not do the cool flyTo animation that you are looking for. So, if you absolutely need to get that smooth pan zoom animation in flyTo, then continue reading below.

I recently came across this exact problem myself and I was able to solve this with a dirty fix that is definitely not the official way to do it, so, if someone knows of a better way, please mention it.

The way I got the zoomLevel at which a marker is visible, is by first getting access to the parent cluster of said marker. Next, I get the bounds of this cluster using the cluster's .getBounds() method (provided by markercluster library). Once I have the bounds of this cluster, I can simply get the required zoom level use the map object's .getBoundsZoom() method (provided by the original leaflet library).

// Assuming `myMarker` is your marker object and `myMap` is your map object

const clusterBounds = myMarker.__parent.getBounds();
const zoomLevel = myMap.getBoundsZoom(clusterBounds);

myMap.flyto(latLng, zoomLevel);

As you can see, accessing the .__parent property of a marker is the only "dirty" part of this otherwise okay approach. While there is a method called .getVisibleParent(), I was not able to find a way to get the immediate parent of cluster.

divadsn commented 6 months ago

@waseemyusuf even better solution:

const parentCluster = marker.__parent;
const zoomLevel = Math.min(map.getMaxZoom(), Math.max(map.getZoom(), parentCluster._zoom + 1));

map.flyTo(marker.getLatLng(), zoomLevel);