Geoserver + Openlayers 拉框查詢
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>OpenLayers</title> <link rel="stylesheet" href="geoserver/ol.css" type="text/css"> <script src="geoserver/ol.js"></script> <script src="bower_components/jquery/dist/jquery.min.js"></script> <link rel="stylesheet" href="plugins/layui-v2.4.3/layui/css/layui.css"> <script src="plugins/layui-v2.4.3/layui/layui.js" charset="utf-8"></script> <link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css"> <#--注意openlayer的版本號,高版本存在es6中新語法不相容的情況--> <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script> <script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script> </head> <style> #map { height: 600px; /*width: 1024px;*/ /* float: left;*/ } </style> <body> <div id="map"> <form class="form-inline"> <label>查詢型別</label> <select id="type"> <option value="None">None</option> <option value="Point">點選</option> <option value="Polygon">多邊形</option> <option value="Circle">拉框</option> </select> </form> </div> <script> var map = new ol.Map({ target: 'map', view: new ol.View({ projection: 'EPSG:4326', center: [104.07, 30.72], zoom: 7 }) }); var wfsParams = { service: 'WFS', version: '1.1.1', request: 'GetFeature', typeName: 'map_dz:tl_lx_g',//圖層名稱,可以是單個或多個 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://192.168.1.113:8080/geoserver/map_dz/wms'; $.ajax({ url: url, data: $.param(wfsParams),//傳參 type: 'GET', dataType: 'jsonp',//解決跨域的關鍵 jsonpCallback: 'loadFeatures'//回撥 }); }, strategy: ol.loadingstrategy.tile(new ol.tilegrid.createXYZ({ maxZoom: 20 })), projection: 'EPSG:4326' }); //回撥函式使用 window.loadFeatures = function (response) { vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(response));//載入要素 }; var vectorLayer = 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 }) }) }); map.addLayer(vectorLayer); var draw; var typeSelect = document.getElementById('type'); var value; var num=10;//用於刪除之前的框,表示號,隨便取一個 function addInteraction() { if (value !== 'None') { if (value === 'Polygon') { draw = new ol.interaction.Draw({ source: vectorLayer.getSource(), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }), type: value }); } else if (value === 'Circle') { draw = new ol.interaction.Draw({ source: vectorLayer.getSource(), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }), type: value, geometryFunction: ol.interaction.Draw.createBox() }); } else if (value === 'Point') { draw = new ol.interaction.Draw({ source: vectorLayer.getSource(), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }), type: value }); } map.addInteraction(draw); //刪除之前draw的部分 draw.on('drawstart',function(evt) { var featureAdd=vectorLayer.getSource().getFeatureById(num); if(featureAdd!=null){ vectorLayer.getSource().removeFeature(featureAdd); } }); //繪圖結束,處理選中部分 draw.on('drawend',function(e){ e.feature.setId(num); var geom=e.feature.getGeometry(); var coor = geom.v; mapSelect(coor); }); } } //選擇事件 typeSelect.onchange = function() { value = typeSelect.value; map.removeInteraction(draw); addInteraction(); }; //draw影象與原始資料相交 function mapSelect(coor) { if(value=='Point') { coor = [coor[0]-0.0001,coor[1]-0.0001,coor[0]+0.0001,coor[1]+0.0001]; } var FILTER = '<Filter xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><BBOX><PropertyName>geom</PropertyName><gml:Envelope srsName="EPSG:4326"><gml:lowerCorner>' + coor[0] + '' + coor[1] + '</gml:lowerCorner><gml:upperCorner>' + coor[2] + '' + coor[3] + '</gml:upperCorner></gml:Envelope></BBOX></Filter>'; getFeature({ typename: 'map_dz:tl_lx_g',//查詢的服務圖層名稱 filter: FILTER,//查詢條件 callback: 'getIdentifyroadGrid'//查詢的回撥函式 }); } var selectNum=[]; var geojsonFormat = new ol.format.GeoJSON({defaultDataProjection: "EPSG:4326"}); function getIdentifyroadGrid(res) { var queryData = []; var features = geojsonFormat.readFeatures(res); for (var nu = 0; nu<selectNum.length;nu++) { var featureSelect=vectorLayer.getSource().getFeatureById(selectNum[nu]); if(featureSelect!=null) { featureSelect.setStyle( new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 255, 1.0)', width: 2 }) })); } } selectNum=[]; for (var i = 0; i < features.length; i++) { var feature = features[i]; console.log(feature); selectNum.push(feature.f); var featureSelectCurrent=vectorLayer.getSource().getFeatureById(feature.f); featureSelectCurrent.setStyle( new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#ff4118', width: 2 }) })); var lxmc = feature.H["lxmc"]; var ldbm = feature.H["ldbm"]; var lxbh = feature.H["lxbh"]; var result = { "lxmc": lxmc, "ldbm": ldbm, "lxbh": lxbh, "setindex": i }; queryData.push(result) } console.log(selectNum); var tableIns=null; var dataTable = "<table class=\"layui-table\" lay-filter=\"demo\" id=\"joinTab\"></table>"; layui.use(['table', 'layer'], function () { var table = layui.table; var layer = layui.layer; var index = layer.open({ type: 1 //Page層型別 , title: '要素屬性' , shade: 0 //遮罩透明度 , anim: 0 //0-6的動畫形式,-1不開啟 , content: dataTable , offset: ['250px', '290px'] , zIndex: 1 , scrollbar: false , resize: false , skin: 'layui-layer-molv' , closeBtn: 2 , btn: ["關閉"] , yes: function (index) { layer.close(index); } , cancel: function () { } }); tableIns = table.render({ elem: "#joinTab", width: "auto", height: "auto", data: queryData, initSort: {field: 'lxbh', type: 'desc'}, cols: [[ {field: 'lxmc', title: '路線名稱', width: 150, align: 'center', sort: true}, {field: 'ldbm', title: '路線編號', width: 150, align: 'center', sort: true}, {field: 'lxbh', title: '路段編碼', width: 150, align: 'center', sort: true} ]] }); layer.style(index, { opacity: 0.8 }); }); if (tableIns) { tableIns.reload({ data: queryData }); } else { // console.log("Do Nothing!"); } } //請求wfs資料 function getFeature(options) { $.ajax(/*'http://192.168.1.113:8080/geoserver/map_dz/wms', */{ type: 'GET', url: 'http://192.168.1.113:8080/geoserver/map_dz/wms', data: { service: 'WFS', version: '1.1.1', request: 'GetFeature', typename: options.typename, srsname: options.srid, outputFormat: 'text/javascript', viewparams: options.viewparams, bbox: (options.extent === undefined) ? undefined : options.extent.join(',') + ',' + options.srid, filter: options.filter }, dataType: 'jsonp', jsonp: 'format_options', jsonpCallback: 'callback:' + options.callback }); } </script> </body> </html> 複製程式碼
2.程式碼解釋
這一部分是主要針對使用者做此功能的時候,遇到的問題進行總結
在引入 Openlayers 的 JS 檔案的時候,注意版本號,5.0+ 的版本中大量應用了ES6 的最新特性,如果直接引入 5.0+ ,可能與前期的專案有所衝突,所以這裡建議使用低版本,同樣能完成拉框查詢

這裡主要通過 Draw 物件進行框選的,Draw 的本質是在圖層上興建 Shape ,那麼在下一次框選的時候,需要把上次 Draw 的框去掉:(回答了網上使用者的提問:openlayers 在重新畫圖(圓或矩形)如何清除之前的圖,Openlayer刪除上一次繪製的圖)
首先記錄框選時,增加的框框的ID

然後在下次框選之前,通過 id 找到上次那個 Feature,並刪掉

對選中的物件進行重新設定顏色,這裡主要通過 Style 屬性進行處理:

在下次選中物件的時候,刪除上次選中物件的樣式 將選中物件的 id 壓到陣列彙總

在下次設定選中物件的樣式之前,遍歷陣列,對上次選中的feature進行樣式設定(設定為原來的樣式)

3.結果



參考
https://www.cnblogs.com/kkyyhh96/p/6379515.html https://blog.csdn.net/songjian1314/article/details/17263865 https://blog.csdn.net/shaxiaozilove/article/details/60780175 https://blog.csdn.net/m0_37659871/article/details/80598589 https://openlayers.org/en/latest/examples/draw-features.html https://openlayers.org/en/latest/examples/draw-shapes.html