Turf.js with Leaflet – Dissolve Features Not Adding to Map Troubleshooting

dissolveleafletturf

Trying to dissolve features with boundaries that touch with Turf.js. They all have a common attribute that is specific in the Turf option example. Console loge console.log(regionsDissolved) results in 'FeatureCollection', features: Array(0)}. Which I think is expected. The results however don't add to my Leaflet map.

// add UC Berkeley regions to map with jQuery

$.getJSON('data/regions-ucb.json', function (data) {
    // refresher question - is this 'data' call an anonymous function passing to an anonymous function above?
    var ucbRegions = L.geoJson(data).addTo(map);

    // create feature collection from ucbRegions
    var features = turf.featureCollection(turf.polygon(ucbRegions.toGeoJSON()), { combine: 'yes' });
    console.log(features)

    // dissolve features
    var regionsDissolved = turf.dissolve(features, { propertyName: 'combine' })
    console.log(regionsDissolved)

    // display dissolved features with red line and add to map
    L.geoJson(regionsDissolved, {

        // style layers so the buffer is visible
        style: function (feature, layer) {
            return {
                color: "green",
                weight: 3
            };
        }
    }).addTo(map);
})

Best Answer

Your turf.featureCollection statement

var features = turf.featureCollection(turf.polygon(ucbRegions.toGeoJSON()), { combine: 'yes' });

has wrong input. turf.polygon method expects polygon coordinates, but you are giving it feature collection ucbRegions.toGeoJSON() as input. Besides that, it's also unnecessary, since data already contains your feature collection.

Since you are dissolving all polygons, also dissolve selector {propertyName: 'combine'} is unnecessary.

Code could then look something like this:

$.getJSON('data/regions-ucb.json', function (data) {
  var ucbRegions = L.geoJson(data).addTo(map);
  var regionsDissolved = turf.dissolve(data);
  L.geoJson(regionsDissolved, {
    style: function (feature, layer) {
      return {
        color: "green",
        weight: 3
      };
    }
  }).addTo(map);
});

This gives the following result, which shows that not all the regions boundaries are overlapping:

enter image description here