天天看點

OpenLayers通路WMS服務并擷取要素的屬性OpenLayers 跨域通路WMS服務并擷取要素的屬性

OpenLayers 跨域通路WMS服務并擷取要素的屬性

整體思路:

1.因為我們這個地圖服務是在Geoserver釋出,要先解決跨域的問題,GeoServer啟動有兩種方式,一種是war存放在tomcat裡啟動,還有一種就是自己啟動,是以要根據具體方式百度;

2.首先定義一個map,資料源裡crossOrigin: ‘anonymous’,跨域要加,通過監聽一個單擊事件getGetFeatureInfoUrl來擷取到點選的WMS要素的url, 通過fetch發送請求得到資料最後展示在頁面裡;

3.最後再小小說明下,如果不是這個坐标系,其他坐标系的話需要進行轉換

我一般借助的是proj4js 坐标系轉換詳情

上代碼

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>跨域WMS通路擷取要素屬性</title>
<link rel="stylesheet"
	href="https://openlayers.org/en/v3.20.1/css/ol.css" target="_blank" rel="external nofollow"  type="text/css">
<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>
<script type="text/javascript"
	src="https://cdn.bootcss.com/proj4js/2.5.0/proj4.js"></script>
</head>
<body>
	<div id="map" class="map"></div>
	<div id="info">&nbsp;</div>
	<script>
    
    //地圖格式 栅格
    var format = 'image/png';
    //xy最大最小
    var bounds = [-124.73142200000001, 24.955967,
                  -66.969849, 49.371735];
    //栅格地圖源
    var source = new ol.source.ImageWMS({
    	crossOrigin: 'anonymous',
        ratio: 1,
        url: 'http://localhost:8082/geoserver/topp/wms',
        params: {'FORMAT': format,
                 'VERSION': '1.1.1',  
              STYLES: '',
              LAYERS: 'topp:states',
        }
      });
    //栅格圖層
    var layers =  [new ol.layer.Image({
    		        source: source
    		      })]
    //投影
    var projection = new ol.proj.Projection({
        code: 'EPSG:4326',
        units: 'm',
        axisOrientation: 'neu',
        global: false
    });
    
    var view = new ol.View({
	    projection: projection
	  })
    		var map = new ol.Map({
    		  layers: layers,
    		  target: 'map',
    		  view: view
    		});
    		 map.getView().fit(bounds,map.getSize());
    		 /**監聽一個單擊事件, 
    		 通過getGetFeatureInfoUrl來擷取到點選的WMS要素的url,
    		 通過fetch發送請求得到資料最後展示在頁面裡
    		 */
    		 map.on('singleclick', function(evt) {
    		        document.getElementById('info').innerHTML = '';
    		        var viewResolution = (view.getResolution());
    		        var url = source.getGetFeatureInfoUrl(
    		            evt.coordinate, viewResolution, 'EPSG:4326',
    		            {'INFO_FORMAT': 'text/html'});
    		        if (url) {
    		            fetch(url)
    		              .then(function (response) { return response.text(); })
    		              .then(function (html) {
    		                document.getElementById('info').innerHTML = html;
    		              });
    		          }
    		        });
 </script>
</body>

</html>
           
OpenLayers通路WMS服務并擷取要素的屬性OpenLayers 跨域通路WMS服務并擷取要素的屬性

最後的結果就是點選某個要素會把要素裡的屬性全部展示出來