[GIS] Leaflet markerClusterGroup ‘undefined is not a function’

clusteringleafletmarkers

I have to create a map with more than 5000 points from a geojson. So I would like to use markercluster plugin with Leaflet.

I wrote the following code with help from the documentation and from other posts (I'm new to webmapping and to programming languages) and the chrome console returns that "L is not defined" for the leaflet.markercluster.js file and that "undefined is not a function" for my line of code with L.markerClusterGroup().

Here is the code :

var clusterGroup = new L.markerClusterGroup();

var points = L.geoJson(gares, {
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng)
      .bindPopup(feature.properties.NOM);
    }
});

clusterGroup.addLayer(points);

map.addLayer(clusterGroup);

Is there someone to help me understanding why it doesn't work ?

Best Answer

You should add the script that loads the markercluster plugin after you've loaded the core leaflet application. The markercluster functionality is based on extended/new classes from Leaflet, so it has to read Leaflet first. So, put this line:

 <script src="https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/leaflet.markercluster.js"></script>

After this one:

<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>