Search code examples
javascriptjqueryleafletgeojsonsweetalert2

Call a function outside onEachFeature leaflet


I want to call a function outside the onEachFeature applied to each countries layer.

The function i want to declare is a PopUp on click layer of Leaflet (Example : If France layer is clicked, call the function showflag as a sweet-alert popup

When I declare and define it inside the onEachFunction, it works perfectly with the following code

$.getJSON("js/test/custom.geojson", function(data) {
    // Apply a popup event to each "Features" of the dataset
   L.geoJSON(data, {
        onEachFeature: function (feature, layer) {
            layer.on('click', function showFlag(){
                Swal.fire({
                    title: "You have selected",
                    icon: "info",
                    html: '<span class="flag-icon flag-icon-'+feature.properties.iso_a2.toLowerCase()+'"></span>'
                })
            });
        }
    }).addTo(map);
});

But when I define it outside the code, it does not work. It will instead show the alert of the first occurence of the GeoJSON data after the script is loaded and it will not respond to any click events afterwards.

$.getJSON("js/test/custom.geojson", function(data) {
    // Apply a popup event to each "Features" of the dataset
   L.geoJSON(data, {
        onEachFeature: function (feature, layer) {
            layer.on('click', showFlag(feature.properties.iso_a2.toLowerCase()));
        }
    }).addTo(map);
});

function showFlag(flag) {
    Swal.fire({
        title: "You have selected",
        icon: "info",
        html: '<span class="flag-icon flag-icon-'+flag+'"></span>'
    })
}

Where I did wrong ?


Solution

  • change your code to:

    $.getJSON("js/test/custom.geojson", function(data) {
        // Apply a popup event to each "Features" of the dataset
       L.geoJSON(data, {
            onEachFeature: function (feature, layer) {
                layer.on('click', showFlag);
            }
        }).addTo(map);
    });
    
    function showFlag(e) {
        var layer = e.target;
        var flag = layer.feature.properties.iso_a2.toLowerCase();
        Swal.fire({
            title: "You have selected",
            icon: "info",
            html: '<span class="flag-icon flag-icon-'+flag+'"></span>'
        })
    }