简体   繁体   中英

Handling ajax-request in leaflet map

I have a very basic leaflet map using leaflet-panel-layers to create a pretty layer control. I have two functions to create my layers and overlays. My data is in external geoJSON-Files what seems to be my problem as leaflet does not offer anything to get an external geoJSON. I also use proj4leaflet library to use the projection given in my json. So google told me to use ajax about which I unfortunately don't know anything. I copy-pasted something like this:

function getOverlays(){
    var url = 'myServerUrl';
    overlays = [];

    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'getJson',
        success: function(response) {
            overlays.push({
                name: "Something",
                layer: L.Proj.geoJson(response, {
                ...
                }
            });
        }
    });
    return overlays;
}

my map is built like this:

var map = L.map('map', {
    layers: layers[0].layer
});
var layers = getBaseLayers();
var overlays = getOverlays();
var panelLayers = new L.Control.PanelLayers(layers,overlays);
map.addControl(panelLayers);

This actually works fine if I want to add the layers to the map directly. But in my case the asynchronous request seems to be ready after my layer switcher is added to my map so the layers don't appear there. Is there any way to solve this simply without diving into callbacks?

Add your control after request has finished. This can be done with a callback function:

function getOverlays(callback){
    var url = 'myServerUrl';
    overlays = [];

    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'getJson',
        success: function(response) {
            overlays.push({
                name: "Something",
                layer: L.Proj.geoJson(response, {
                ...
                }
            });
            callback(overlays)
        }
    });
    return overlays;
}

var map = L.map('map', {
    layers: layers[0].layer
});
var layers = getBaseLayers();
getOverlays(function(overlays){
    var panelLayers = new L.Control.PanelLayers(layers,overlays);
    map.addControl(panelLayers);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM