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) {

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 Answer 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 and acknowledge you have read our privacy policy.

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