我有一个非常基本的传单地图,使用 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);
});
这篇关于在传单地图中处理 ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
检查一个多边形点是否在传单中的另一个内部Check if a polygon point is inside another in leaflet(检查一个多边形点是否在传单中的另一个内部)
更改传单标记群集图标颜色,继承其余默认 CSSChanging leaflet markercluster icon color, inheriting the rest of the default CSS properties(更改传单标记群集图标颜色,继承其余默认
触发点击传单标记Trigger click on leaflet marker(触发点击传单标记)
如何更改 LeafletJS 中的默认加载磁贴颜色?How can I change the default loading tile color in LeafletJS?(如何更改 LeafletJS 中的默认加载磁贴颜色?)
将外部geojson添加到传单层Add external geojson to leaflet layer(将外部geojson添加到传单层)
将 Leaflet 图层控件添加到侧边栏Adding Leaflet layer control to sidebar(将 Leaflet 图层控件添加到侧边栏)