1. 程式人生 > >openlayers 3加載GeoServer發布的wfs類型服務

openlayers 3加載GeoServer發布的wfs類型服務

asc 改變 targe net import eps 出現 IT class

轉:https://blog.csdn.net/u013323965/article/details/52449502

問題產生:

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中調用會存在跨域的問題產生 但出現了如圖所示的問題,查看開發工具發現json數據沒有套上回調名。 技術分享圖片


調用代碼

在代碼中,我將輸出格式改變為javascript來解決jsonp 技術分享圖片
 1 //參數字段  
 2     var wfsParams = {    
 3             service : ‘WFS‘,    
 4             version : ‘1.0.0‘,    
 5             request : ‘GetFeature‘,    
 6             typeName : ‘cite:bou2_4p‘,  //圖層名稱     
 7             outputFormat : ‘text/javascript‘,  //
重點,不要改變 8 format_options : ‘callback:loadFeatures‘ //回調函數聲明 9 }; 10 11 var vectorSource = new ol.source.Vector({ 12 format: new ol.format.GeoJSON(), 13 loader: function(extent, resolution, projection) { //加載函數 14 var
url = ‘http://localhost:8080/geoserver/wfs‘; 15 $.ajax({ 16 url: url, 17 data : $.param(wfsParams), //傳參 18 type : ‘GET‘, 19 dataType: ‘jsonp‘, //解決跨域的關鍵 20 jsonpCallback:‘loadFeatures‘ //回調 21 22 }); 23 }, 24 strategy: ol.loadingstrategy.tile(new ol.tilegrid.createXYZ({ 25 maxZoom: 25 26 })), 27 projection: ‘EPSG:4326‘ 28 }); 29 //回調函數使用 30 window.loadFeatures = function(response) { 31 vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(response)); //載入要素 32 33 }; 34 var vectorLayer = new ol.layer.Vector({ 35 source: vectorSource 36 });
View Code 但出現了如圖所示的問題,查看開發工具發現json數據沒有套上回調名。 技術分享圖片

問題的解決

問題應該是在geoserver中產生的,後來在geoserver的web.xml中發現,jsonp的註釋沒有被註銷,導致無法輸出jsonp 技術分享圖片 最後結果,看到已經沒有問題 技術分享圖片

openlayers 3加載GeoServer發布的wfs類型服務