Bergen88
Bergen88

Reputation: 177

Is there a way to filter geojson by clicking polygon in Leaflet?

I have implemented a geojson filter using toggle buttons with a LayerGroup, but would like to know if anyone has been successful with same behavior using on-map mouseclicks.

Example: map of world countries. click on Italy polygon results in only Italy being visible. Click outside Italy to show all countries again. Hope my question is clear.

Upvotes: 0

Views: 984

Answers (1)

iH8
iH8

Reputation: 28678

It's just a matter of hooking on to the click event of the layer, clearing the group and add that single layer. Also hook on to the map click, remove the single layer and restore the rest. Here's a quick-n-dirty example:

// vars to store stuff
var geojson, source, selected;

// Load the collection
$.getJSON(url, function (collection) {
    // Store collection for later use
    source = collection;
    // Create layer and add collection
    geojson = L.geoJson(collection, {
        // On each feature in collection
        'onEachFeature': function (feature, layer) {
            // Attach click handler
            layer.on('click', function () {
                // Set selected flag
                selected = true;
                // Clear the entire layer
                geojson.clearLayers();
                // Add the feature
                geojson.addData(feature);
                // Fit layer to map
                map.fitBounds(layer.getBounds());
            });
         }
    }).addTo(map);
});

// Attach to map click
map.on('click', function () {
    // Check if something's selected
    if (selected) {
        // Clear the entire layer
        geojson.clearLayers();
        // Restore the collection
        geojson.addData(source);
        // Fit map to collection
        map.fitBounds(geojson.getBounds());
    }
});

Here's a working example on Plunker: http://plnkr.co/edit/o5Q0p3?p=preview

Upvotes: 3

Related Questions