jawadxiv
jawadxiv

Reputation: 59

Leaflet foreach feature auto trigger mouseover function

I am stuck with a situation where I have to create a dashboard application similar to ChoroplethExample. But the only problem is I have to iterate between all states(Features in geoJSON) and pause for like 3 seconds in every iteration.

I found this topic where mouseover trigger example is given. But how can we use it for this case.

Below is the function that needs to be fired in every iteration: LeafletExample

function highlightFeature(e) {
var layer = e.target;

layer.setStyle({
    weight: 5,
    color: '#666',
    dashArray: '',
    fillOpacity: 0.7
});

if (!L.Browser.ie && !L.Browser.opera) {
    layer.bringToFront();
  }
}

Upvotes: 0

Views: 768

Answers (1)

iH8
iH8

Reputation: 28688

You can use L.GeoJSON's eachLayer method to iterate over the layers and then use highlightFeature method on the current layer and resetHighlight method on the previous layer (if any).

Remove current interaction:

function onEachFeature(feature, layer) {
    layer.on({
        //mouseover: highlightFeature,
        //mouseout: resetHighlight,
        //click: zoomToFeature
    });
}

Add iterator:

// Variables for storing currently highlighted feature and delay amount
var highlight, delay = 0;

// Iterate over each layer in the geojsonlayer
geojson.eachLayer(function (layer) {

    // Mimick event object because highlightFeature and resetHighlight
    // expect an object with the layer as target property
    layer = {'target': layer};

    // Up the delay amount
    delay = delay + 3000;

    setTimeout(function() {

        // Check if there is a highlight, if so reset
        if (highlight) {
            resetHighlight(highlight);
        }

        // Highlight current and store
        highlightFeature(layer);
        highlight = layer;

    }, delay);
});

Example: http://plnkr.co/edit/QD2uHv?p=preview

Upvotes: 1

Related Questions