derdida
derdida

Reputation: 14904

Mapbox.js GEOJson with Markercluster

I would like to implement GEOJson with MarkerCluster with mapbox.js.

Without Markercluster, everything works fine:

  $.ajax({
        url: 'dashboard/geoJSON',
        dataType: 'json',
        type: 'POST',
        success: function(geojson) {

            locations = L.mapbox.featureLayer().addTo(map)
            locations.on('layeradd', function (e) {
                var marker = e.layer;
                markers.push(marker);
            });

            locations.setGeoJSON(geojson);

            ...

But when ill try to implement MarkerCluster, it only shows 1 marker

        ...
        success: function(geojson) {

            locations = L.mapbox.featureLayer().addTo(map)
            var clusterGroup = new L.MarkerClusterGroup();
            locations.on('layeradd', function (e) {
                var marker = e.layer;
                markers.push(marker);
                clusterGroup.addLayer(markers);
            });
            locations.setGeoJSON(geojson);
            map.addLayer(clusterGroup);

And shows me the following error:

TypeError: t.onAdd is not a function

Can anyone help me out, how can i successfully combine markercluster with GEOJson from an remote server? Thanks in advance

// edit: Found an different example where it already works using:

      var markers = L.markerClusterGroup();

      var geoJsonLayer = L.geoJson(geojson, {
          onEachFeature: function (feature, layer) {

          }
       });
       markers.addLayer(geoJsonLayer);

       map.addLayer(markers);    

       map.fitBounds(markers.getBounds());

But now it looses my "default" styling with properties like "marker-color" - "marker-size".

How can i style my markers now?

Mapbox is a little bit weird, it looks like there are always at least 10 ways to solve such things ;)

Upvotes: 0

Views: 304

Answers (1)

ghybs
ghybs

Reputation: 53205

If your markers variable is an array (as you use .push() on it), you cannot use clusterGroup.addLayer(markers). You could have used .addLayers(markers) (with an "s" on addLayers).

I guess you would not like to add the entire array at each "layeradd" event anyway, so maybe you meant clusterGroup.addLayer(marker) (without the "s" on marker, i.e. your individual marker / feature).

By the way, you could have used the onEachFeature option of your L.mapbox.featureLayer() instead of using the event listener.

Finally, do not add your Feature Group as well to the map. That is the one that is adding your only marker currently. You want to let your cluster group to handle the markers adding / removal from map automatically.

Upvotes: 1

Related Questions