How to specify custom cluster marker for a Google map

Viewed 1936

I have a Google map with markers placed, with clustering.

I'm able to easily change the marker icon with code like this:

marker = new google.maps.Marker({
    position: {
        lat: location_data.lat,
        lng: location_data.lng
    },
    map: map,
    icon: img_url + 'map-marker.svg',
});

However, I'm stuck on changing the cluster icon. This code works well to do the actual clustering:

const marker_clusterer = new markerClusterer.MarkerClusterer({
    map: map,
    markers: markers
});

I've found code out there suggesting this:

const marker_clusterer = new markerClusterer.MarkerClusterer({
    map: map,
    markers: markers,
    renderer: {
        imagePath: img_url + 'map-cluster'
    }
});

Where map-cluster is the prefix for a bunch of files e.g. map-cluster1.svg. This gives me the error: 'Uncaught TypeError: e.renderer.render is not a function'.

I've also tried this:

const marker_clusterer = new markerClusterer.MarkerClusterer({
    map: map,
    markers: markers,
    renderer: {
        styles: [{
            url: img_url + 'map-cluster1.svg',
        }]
    }
});

I get the same error again for this.

There are other code examples which don't seem to bear any relation to the code I'm already working with, heaps of custom objects (e.g. https://gabrielwadi.medium.com/custom-cluster-marker-for-google-maps-how-to-8a7b858e2879). The API docs just point to this kind of unhelpful page: https://googlemaps.github.io/js-markerclusterer/interfaces/MarkerClustererOptions.html#renderer I guess I'm not specifying the custom 'renderer' properly, but all the code samples I've found are either simple and don't work (above), or too complex for me to know where to begin.

Does anyone have any pointers? I'm referencing https://maps.googleapis.com/maps/api/js as my main API script, and https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js for clustering.

1 Answers

The MarkerClusterer expects an interface with a render method:

const renderer = {
  render: ({ count, position }) =>
    new google.maps.Marker({
      label: { text: String(count), color: "white", fontSize: "10px" },
      position,
      // adjust zIndex to be above other markers
      zIndex: Number(google.maps.Marker.MAX_ZINDEX) + count,
    }),
};

new markerClusterer.MarkerClusterer({
  map,
  markers,
  renderer,
});

picture of refdocs

Related