使用Javascript循环将GeoServer的Leaflet GeoJSON图层添加到数组

我正在尝试使用循环将GeoJSON图层添加到数组,然后在地图上显示它们.

我的目标是拥有这样的变量:scenario_json [1] = layer1,scenario_json [2] = layer2,依此类推…

    myURL = [
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase1&maxFeatures=400&maxFeatures=400&outputFormat=json&format_options=callback:getJson",
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase2&maxFeatures=400&outputFormat=json&format_options=callback:getJson",
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase3&maxFeatures=400&outputFormat=json&format_options=callback:getJson"
];


$.getScript('src/leaflet.js');

for(i=0;i<=myURL.length;i++){

    var scenario_json = {};
    scenario_json[i] = new L.GeoJSON();

    function getJson(data){
        console.log(data)
        scenario_json[i].addData(data); 
    }

    $.ajax({
        url: myURL[i],
        jsonp: false,
        dataType: "json",
        jsonpCallback: "getJson",
        success: getJson
    })
};

我在控制台中收到以下响应:

Object {readyState: 1}
VM3689:10 Object {type: "FeatureCollection", totalFeatures: 386, features: Array[386], crs: Object}
VM3689:11 Uncaught TypeError: Cannot read property 'addData' of undefinedgetJson @ VM3689:11c @ jquery.min.js:3p.fireWith @ jquery.min.js:3k @ jquery.min.js:5r @ jquery.min.js:5
VM3689:10 Object {type: "FeatureCollection", totalFeatures: 377, features: Array[377], crs: Object}
VM3689:11 Uncaught TypeError: Cannot read property 'addData' of undefined

知道为什么它不起作用吗?

谢谢

解决方法:

发生的情况是,在getJson回调的上下文中不存在case_json.

我不确定您为什么使用JSONP,因为这是发出跨域请求的旧解决方法.您不需要它,因为目前您是在本地主机/相同域中工作.您可以尝试将纯XHR与JSON一起使用,而不是JSONP.

从您的网址中删除formatOptions:

myURL = [
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase1&maxFeatures=400&maxFeatures=400&outputFormat=json",
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase2&maxFeatures=400&outputFormat=json",
    "http://localhost:8080/geoserver/jonquiere_local/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=jonquiere_local:buildings_phase3&maxFeatures=400&outputFormat=json"
];

切换到$.getJSON:

for (i = 0; i <= myURL.length; i++) {

    var scenario_json = {};

    $.getJSON(myURL[i], function (data) {
        scenario_json[i] = new L.GeoJSON(data);
    }).done(function () {
        console.log('$.getJSON Done!');
    }).fail(function () {
        console.log('$.getJSON Fail!');
    });
}

这是关于Plunker的一个工作示例:http://plnkr.co/edit/fNf9CDTBCCsj3cavVjJY?p=preview

PS.如果您遇到跨域问题,可以通过在GeoServer上启用CORS来简单解决.

上一篇:javascript-如何将click事件绑定到Leaflet canvas GridLayer


下一篇:javascript-Leaflet.js快速入门基本示例演示