JustFly1984 / react-google-maps-api

React Google Maps API
MIT License
1.76k stars 426 forks source link

Custom clustering algoritm #2905

Open DmitryDadeco opened 2 years ago

DmitryDadeco commented 2 years ago

Is it possible to change clustering algorithm in MarkerCluster component? I need to cluster markers inside country. https://github.com/JustFly1984/react-google-maps-api/blob/develop/packages/react-google-maps-api/src/components/addons/MarkerClusterer.tsx

Or use undocumented component GoogleMarkerClusterer with options like in MarkerCluster (for example i need to calculator and options.styles) https://github.com/JustFly1984/react-google-maps-api/blob/develop/packages/react-google-maps-api/src/components/addons/GoogleMarkerClusterer.tsx

bradley commented 3 months ago

I'm having similar issues and hesitant to even offer this advice because using the (as you say) undocumented GoogleMarkerClusterer component seems to lack a lot of the useful props like onLoad that some other bug workarounds require from my searching so far, but if you want to use GoogleMarkerClusterer and send options like the one you asked about, you can do so like this:

import React from "react";
import { GridAlgorithm } from "@googlemaps/markerclusterer";
import { GoogleMarkerClusterer } from "@react-google-maps/api";

// ... define myRenderFunction if you want a custom renderer...

const CLUSTER_OPTIONS = {
  algorithm: new GridAlgorithm({ maxZoom: 15 }), // or what have you
  renderer: { render: myRenderFunction },  // define myRenderFunction if you want a custom renderer
};

const MyCustomClusterer = props => {
  const { children } = props;

  return (
    <GoogleMarkerClusterer options={CLUSTER_OPTIONS}>
      { (clusterer) => (children(clusterer)) }
    </GoogleMarkerClusterer>
  );
};

Usage:


<MyCustomClusterer>
  {
    (clusterer) => (
      items.map(item => (
        <MyCustomMarker
          key={`marker-${item.key}`}
          item={item}
          // Be sure to set this on the actual marker in MyCustomMarker...
          clusterer={clusterer} 
        />
      ))
    )
  }
</MyCustomClusterer>