Markercluster with Mapbox marker data
by Anas Zaki
HTML
<script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css">
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/leaflet.markercluster.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.css' rel='stylesheet' />
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.Default.css' rel='stylesheet' />
<div id='map'></div>
CSS
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
JavaScript
L.mapbox.accessToken = 'pk.eyJ1IjoiaXdhbm5hZmx5dXAiLCJhIjoic3g4WVR2YyJ9.qcDUEK2Z2fOd453_raZ8tw';
// Here we don't use the second argument to map, since that would automatically
// load in non-clustered markers from the layer. Instead we add just the
// backing tileLayer, and then use the featureLayer only for its data.
var map = L.mapbox.map('map')
.setView([31.822, -9.503], 7)
.addLayer(L.mapbox.tileLayer('iwannaflyup.hmcd822n'));
// Since featureLayer is an asynchronous method, we use the `.on('ready'`
// call to only use its marker data once we know it is actually loaded.
L.mapbox.featureLayer('iwannaflyup.hmcd822n').on('ready', function(e) {
// The clusterGroup gets each marker in the group added to it
// once loaded, and then is added to the map
var clusterGroup = new L.MarkerClusterGroup();
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
});
map.addLayer(clusterGroup);
});