I'm trying to use MarkerClusterGroup on a leaflet map. I have the error L.MarkerClusterGroup is not a function
. I've read the related threads, but they are only valid for versions below leaflet 1.7.
I'm using React with webpack.
import { Icon, Marker, Circle, LatLngBounds, Popup, DivIcon } from "leaflet";
import "leaflet.markercluster";
const divIcon = new DivIcon();
const markersCluster = L.MarkerClusterGroup({
chunkedLoading: true,
iconCreateFunction: function (cluster) {
return divIcon({
html: cluster.getChildCount(),
className: "mycluster",
iconSize: null,
});
},
});
I've also tried to import L
globally:
import * as L from "leaflet";
import "leaflet.markercluster";
const divIcon = new L.DivIcon();
const markersCluster = L.MarkerClusterGroup({
chunkedLoading: true,
iconCreateFunction: function (cluster) {
return divIcon({
html: cluster.getChildCount(),
className: "mycluster",
iconSize: null,
});
},
});
How to fix this?
Depending on your build engine, the imported L
namespace from "leaflet" may not be augmented with MarkerClusterGroup
(from leaflet.markercluster plugin) unfortunately.
But you can resort to using window.L
instead, which is always augmented by the plugin.
BTW, either use the class constructor form with new
keyword: new window.L.MarkerClusterGroup()
, or use the factory form with lowerCamelCase: L.markerClusterGroup()
import * as L from "leaflet";
import "leaflet.markercluster";
console.log(window.L === L); // false...
const divIcon = new L.DivIcon();
const markersCluster = new window.L.MarkerClusterGroup({ // Use window.L for plugins
chunkedLoading: true,
iconCreateFunction: function (cluster) {
return divIcon({
html: cluster.getChildCount(),
className: "mycluster",
iconSize: null,
});
},
});
Live demo: https://stackblitz.com/edit/js-ojki89?file=index.js