一、简单介绍
OpenLayers 读取 WMS 服务与 OpenLayers 读取 GeoServer 发布的地图服务 类似;
其中WMS介绍参见:
https://zhuanlan.zhihu.com/p/73973319;
https://zhuanlan.zhihu.com/p/74273452;
二、代码
本次 Demo 主要介绍读取 GeoServer 发布的 WMS 地图服务,并且绘制矢量
<template>
<div>
<div id="map" ref="rootmap">
</div>
<label>Shape type </label>
<select id="selectType">
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="Square">Square</option>
<option value="Box">Box</option>
<option value="None">None</option>
</select>
</div>
</template>
<script>
import 'ol/ol.css';
import { Map,View } from 'ol';
import Feature from 'ol/Feature';
import {Tile as TileLayer, Image as ImageLayer,Vector as VectorLayer} from 'ol/layer';
import {Point, LineString, Polygon} from 'ol/geom'
import {OSM, ImageArcGISRest,TileWMS,ImageWMS,Vector as VectorSource} from 'ol/source';
import Draw from 'ol/interaction/Draw'
import {createRegularPolygon,createBox} from 'ol/interaction/Draw'
export default{
name: 'OlGeoserveDraw',
data(){
return{
map: null,
typeSelect: null,
draw: null,
vectorSource: null
};
},
mounted(){
var url = 'http://localhost:8080/geoserver/ws-world/wms';
this.vectorSource = new VectorSource();
let vectorLayer = new VectorLayer({
source: this.vectorSource
});
this.map = new Map({
target: "map",
layers: [
new TileLayer({
source: new OSM() //这个会出现底图
}),
new ImageLayer({ //TileLayer、ImageLayer
source: new ImageWMS({ //TileWMS、ImageWMS
ratio: 1,
params: {
'FORMAT': 'image/jpeg',
'VERSION': '1.1.0',
'LAYERS': 'ws-world:ws-group',
'STYLES': '',
},
url: url
})
}),
vectorLayer
],
view: new View({
projection: 'EPSG:4326', //当添加投影坐标时,无法进行绘制
center: [0, 0],
zoom: 4
})
});
this.typeSelect = document.getElementById('selectType');
this.typeSelect.addEventListener('change', () => {
// 移除Draw绘图控件
this.map.removeInteraction(this.draw);
this.addInteraction();
});
this.addInteraction();
},
methods:{
addInteraction(){
let type = this.typeSelect.value;
if(type !== 'None'){
let geometryFunction;
switch(type){
case "Square":
type = 'Circle';
// 生成规则的四边形的图形函数
geometryFunction = createRegularPolygon(4);
break;
case 'Box':
type = 'Circle';
// 生成盒形状的图形函数
geometryFunction = createBox();
break;
default:break;
}
// 初始化Draw绘图控件
this.draw = new Draw({
source: this.vectorSource,
type: type,
geometryFunction: geometryFunction
});
// 将Draw绘图控件加入Map对象
this.map.addInteraction(this.draw);
}
}
}
};
</script>
<style>
#map{
height:800px;
width: 1400px;
}
/*隐藏ol的一些自带元素*/
.ol-attribution,.ol-zoom { display: none;}
</style>
三、最后结果如下图所示