openlayer3加载geoserver发布的WFS服务

来源:互联网 发布:下载伴奏的软件 编辑:程序博客网 时间:2024/05/01 11:39

问题来源

openlayer3加载WFS存在跨域问题,需要用jsonp解决,而jsonp需要用script加载,但加载有误,如图所示,读取cite:bou2_4p图层的GeoJSON

载入地址是这样的http://localhost:8080/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite:bou2_4p&maxFeatures=20000000&outputFormat=application%2Fjson
(与WMS不同,真正的发布地址并不是这个)

在geoserver中看到,它输出的格式是json,但如果在js中调用会存在跨域的问题产生

调用代码

在代码中,我将输出格式改变为javascript来解决jsonp
//参数字段    var wfsParams = {              service : 'WFS',              version : '1.0.0',              request : 'GetFeature',              typeName : 'cite:bou2_4p',  //图层名称               outputFormat : 'text/javascript',  //重点,不要改变            format_options : 'callback:loadFeatures'  //回调函数声明        };   var vectorSource = new ol.source.Vector({           format: new ol.format.GeoJSON(),           loader: function(extent, resolution, projection) {  //加载函数             var url = 'http://localhost:8080/geoserver/wfs';               $.ajax({                   url: url,                   data : $.param(wfsParams),   //传参                 type : 'GET',                   dataType: 'jsonp',   //解决跨域的关键                 jsonpCallback:'loadFeatures'  //回调                                });           },           strategy: ol.loadingstrategy.tile(new ol.tilegrid.createXYZ({               maxZoom: 25           })),           projection: 'EPSG:4326'       });        //回调函数使用  window.loadFeatures = function(response) {           vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(response));  //载入要素                };       var vectorLayer = new ol.layer.Vector({           source: vectorSource     });       map.addLayer(vectorLayer);  
但出现了如图所示的问题,查看开发工具发现json数据没有套上回调名。


问题的解决

问题应该是在geoserver中产生的,后来在geoserver的web.xml中发现,jsonp的注释没有被注销,导致无法输出jsonp


最后结果,看到已经没有问题

2 0