一開始在官網上找到了例子,官網的例子如下:
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
'outputFormat=application/json&srsname=EPSG:3857&' +
'bbox=' + extent.join(',') + ',EPSG:3857';
},
strategy: ol.loadingstrategy.bbox
});
var vector = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
把裏面的URL改成自己的,會發現存在跨域的問題,問題如下:
然後百度了下,有人給出了方法,下面是代碼:
//參數字段
var wfsParams = {
service : 'WFS',
version : '1.0.0',
request : 'GetFeature',
typeName : 'test:XKD_Shapefile', //圖層名稱
outputFormat : 'text/javascript', //重點,不要改變
//outputFormat : 'application/json', //重點,不要改變
format_options : 'callback:loadFeatures' //回調函數聲明
};
//使用 Ajax 獲取 json 時,存在跨域限制,不能這樣調用;而 jsonp 實際是請求一個 script,然後允許裏面的代碼。
//使用 jsonp 方式,但返回結果確實 json,自然出錯,無法運行
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' //回調
});
},
projection: 'EPSG:4326'
});
//回調函數使用
var loadFeatures = function(response) {
alert("loadFeatures success!");
vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(response)); //載入要素
};
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
用了這個方法,還是不行,停滯了好半天。。。。。。
後來想起之前看到的一個例子:
就試了試打開GeoServer的ENABLE_JSONP,一開始還不知道怎麼打開這個ENABLE_JSONP
是這樣打開的:在GeoServer安裝目錄下打開webapps->geoserver->WEB-INF,打開裏面的web.xml文件
這兩個說的都是同一個問題。。。。只怪自己自動忽略了。。。。
注意下面的框起來的一開始是註釋掉的,把註釋去掉
然後重啓一下GeoServer就行了
我的點數據就加載進來了(9個小圓圈):
注意還需引入Jquery頭文件
參考例子:
https://blog.csdn.net/tuoxinquyu/article/details/76090821
https://blog.csdn.net/tuoxinquyu/article/details/76090821