在传单地图中处理 ajax 请求
我有一个非常基本的传单地图,使用 leaflet-panel-layers
创建漂亮的图层控件.我有两个函数来创建我的图层和叠加层.我的数据在外部 geoJSON 文件中,这似乎是我的问题,因为传单没有提供任何东西来获取外部 geoJSON.我还使用 proj4leaflet
库来使用我的 json 中给出的投影.所以谷歌告诉我使用ajax,不幸的是我对此一无所知.我复制粘贴了这样的内容:
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);
});
相关文章