Vue+OpenLayers学习系列(四)OpenLayers 加载 WMS 地图服务(GeoServer)

本文介绍如何使用OpenLayers读取GeoServer发布的WMS地图服务并进行矢量绘制,包括代码示例和实现步骤。

一、简单介绍

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 &nbsp;</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>

三、最后结果如下图所示

 

 

 

 

 

 

在整合 Spring Boot、Vue 3 和 OpenLayers 6 进行地图开发时,需要从前端与后端的通信、地图渲染、数据交互等多个方面进行设计和实现。以下是详细的实现方案: ### 3.1 前后端通信架构设计 Spring Boot 作为后端服务提供 RESTful API 接口,Vue 3 作为前端框架通过 Axios 或 Fetch API 与后端进行数据交互。前后端分离架构下,推荐使用 CORS 配置解决跨域问题。 Spring Boot 后端配置示例: ```java @Configuration @EnableWebMvc public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true); } } ``` ### 3.2 Vue 3 与 OpenLayers 6 集成 在 Vue 3 中引入 OpenLayers 6 可以使用 CDN 或 npm 安装方式。推荐使用 npm 方式以便于版本管理和模块化开发。 安装 OpenLayers: ```bash npm install ol ``` 创建地图组件示例: ```vue <template> <div id="map" class="map"></div> </template> <script> import { Map, View } from 'ol'; import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; export default { mounted() { const map = new Map({ target: 'map', layers: [ new TileLayer({ source: new OSM() }) ], view: new View({ center: [0, 0], zoom: 2 }) }); } }; </script> <style scoped> .map { width: 100%; height: 100vh; } </style> ``` ### 3.3 地图数据交互与服务集成 结合 PostGIS 数据库与 GeoServer 服务,前端可通过 WMS/WFS 协议请求地图数据OpenLayers 支持直接调用 GeoServer 提供的 WMS 服务。 示例:加载 GeoServerWMS 图层 ```javascript import { bbox as bboxStrategy } from 'ol/loadingstrategy'; import { GeoJSON } from 'ol/format'; import { bbox as bboxStrategy } from 'ol/loadingstrategy'; import { bbox as bboxStrategy } from 'ol/loadingstrategy'; const vectorSource = new VectorSource({ format: new GeoJSON(), url: function (extent) { return 'http://geoserver:8080/geoserver/wfs?service=WFS&' + 'version=2.0.0&request=GetFeature&typeNames=workspace:layername&' + 'outputFormat=application/json&srsname=EPSG:3857&' + 'bbox=' + extent.join(',') + ',EPSG:3857'; }, strategy: bboxStrategy }); ``` ### 3.4 动态图层与交互功能实现 OpenLayers 提供丰富的交互功能,如点击、拖拽、缩放等。结合 Vue 3 的响应式机制,可以实现地图与业务逻辑的联动。 示例:添加点击事件获取地图坐标 ```javascript import { click } from 'ol/events/condition'; map.on('singleclick', function (evt) { const coordinate = evt.coordinate; alert('Clicked at ' + coordinate); }); ``` ### 3.5 前端地图组件与业务数据绑定 在 Vue 3 中,可以将地图组件与 Vuex 状态管理器结合,实现地图状态与业务数据的同步。 示例:使用 Vuex 管理地图缩放级别 ```javascript // store.js import { createStore } from 'vuex'; export default createStore({ state: { zoomLevel: 2 }, mutations: { setZoomLevel(state, level) { state.zoomLevel = level; } }, actions: { updateZoomLevel({ commit }, level) { commit('setZoomLevel', level); } } }); ``` 地图组件中绑定 zoom 状态: ```vue <template> <div id="map" class="map"></div> </template> <script> import { Map, View } from 'ol'; import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; export default { computed: { zoomLevel() { return this.$store.state.zoomLevel; } }, mounted() { const map = new Map({ target: 'map', layers: [ new TileLayer({ source: new OSM() }) ], view: new View({ center: [0, 0], zoom: this.zoomLevel }) }); map.getView().on('propertychange', (evt) => { if (evt.key === 'zoom') { this.$store.dispatch('updateZoomLevel', map.getView().getZoom()); } }); } }; </script> ``` ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值