0

I'm using getJSON to draw points in Leaflet, this is the code:

function cargarpapes(movibles){
    $.getJSON("papeleras1.php", function(data) {           
        papesjson = L.geoJson(data, {
            onEachFeature: function (feature, layer) {
                layer.bindPopup(feature.properties.codigo);
            }
        });
        papesjson.addTo(map);          
    });
}

My question is simple, why I can not use the method papesjson.addTo(map); out of $.getJSON(), even when I have declared my variable papesjson as global at first

1

Because $.getJSON() is asynchronous. So only after your request to papeleras1.php get finished you can add it to the map.

You could add a listener to check when this happens. Like:

map.on('layeradd', function(layer, layername){
    //some action
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.