0
votes

I'm using react-leaflet. to show the map in my react app. I'm also showing marker on the map too. The problem is the zoom level is not appropriate because sometimes the marker might be quite near to each other and sometimes they will be very far apart. Is there any way to set the zoom level depending on the distance of the markers so that the user can see all the markers at once?

Here is my code


<Map center={center} maxZoom={9} zoom={5}>
  <MarkerClusterGroup showCoverageOnHover={false}>
    {
      markers.map(({fillColor, position, id}) => 
         <CircleMarker fillColor={fillColor} color={darken(0.1, fillColor)} radius={10} fillOpacity={1} key={id} center={position} onClick={this.onClick} />
    }
  </MarkerClusterGroup>
</Map>

P.S: My react-leaflet version is 2.4.0

1
@VivekDoshi is there any way to do it without using ref?Gardezi

1 Answers

0
votes

Assuming MarkerClusterGroup is a component from react-leaflet-markercluster package, the following example demonstartes how to auto-zoom to cover visible markers:

function CustomLayer(props) {
  const groupRef = useRef(null);
  const { markers } = props;
  const mapContext = useLeaflet();
  const { map} = mapContext; //get map instance

  useEffect(() => {
    const group = groupRef.current.leafletElement; //get leaflet.markercluster instance  
    map.fitBounds(group.getBounds());  //zoom to cover visible markers
  }, []);

  return (
    <MarkerClusterGroup ref={groupRef} showCoverageOnHover={false}>
      {markers.map(({ fillColor, position, id }) => (
        <CircleMarker
          fillColor={fillColor}
          radius={10}
          fillOpacity={1}
          key={id}
          center={position}
        />
      ))}
    </MarkerClusterGroup>
  );
}

Usage

function MapExample(props) {
  const { markers, center } = props;
  return (
    <Map center={center} maxZoom={9} zoom={5}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      <CustomLayer markers={markers} />
    </Map>
  );
}