geoserver+openlayers做地图展示,添加标注,删除标注,vue版本,前后端分离版

1、下载依赖
npm install ol
2、引入代码
<template>
  <div class="" style="width: 95%; height: 95%">
    <div style="width: 100%; height: 100%" id="map" ref="rootmap"></div>
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import { Tile as TileLayer } from "ol/layer";
import { WMTS } from "ol/source";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { Projection } from "ol/proj";
import { mapGetters } from "vuex";
import FullScreen from "ol/control/FullScreen";
import ScaleLine from "ol/control/ScaleLine";
import ZoomSlider from "ol/control/ZoomSlider";
import MousePosition from "ol/control/MousePosition";
import { defaults } from "ol/control";
// 图上图标相关
import OlFeature from "ol/Feature";
import OlGeomPoint from "ol/geom/Point";
import OlLayerVector from "ol/layer/Vector";
import OlSourceVector from "ol/source/Vector";
import OlStyleStyle from "ol/style/Style";
import OlStyleIcon from "ol/style/Icon";
import Overlay from "ol/Overlay";
// 用来添加相关文字描述的
// import Text from 'ol/style/Text'
// import Fill from 'ol/style/Fill'
const baseUrl = "http://map.teacha.top/geoserver/gwc/service/wmts";
const gridsetName = "EPSG:4326";
const gridNames = [
  "EPSG:4326:4",
  "EPSG:4326:5",
  "EPSG:4326:6",
  "EPSG:4326:7",
  "EPSG:4326:8",
  "EPSG:4326:9",
  "EPSG:4326:10",
  "EPSG:4326:11",
  "EPSG:4326:12",
  "EPSG:4326:13",
  "EPSG:4326:14",
  "EPSG:4326:15",
  "EPSG:4326:16",
  "EPSG:4326:17",
  "EPSG:4326:18",
  "EPSG:4326:19",
]; //切片名
const style = "";
const format = "image/png";
const layerName = "xtmap:6-1";
const resolutions = [
  0.0439453125,
  0.02197265625,
  0.010986328125,
  0.0054931640625,
  0.00274658203125,
  0.001373291015625,
  6.866455078125e-4,
  3.433227539062e-4,
  1.716613769531e-4,
  8.58306884766e-5,
  4.29153442383e-5,
  2.14576721191e-5,
  1.07288360596e-5,
  5.3644180298e-6,
  2.6822090149e-6,
  1.3411045074e-6,
]; //分辨率
const baseParams = [
  "VERSION",
  "LAYER",
  "STYLE",
  "TILEMATRIX",
  "TILEMATRIXSET",
  "SERVICE",
  "FORMAT",
];
//const map = []
export default {
  name: "lq-map",
  data() {
    return {
      map: [],
      layers: [], // 存放标注点。
      dataList: [
        {
          popuId: 22202,
          correctionTypeStr: "XXXXXXX",
          areaName: "XXXX",
          name: "XX",
          lon: "108.99316336631775",
          id: 103,
          personNumber: null,
          residenceAddress: "XXXXXXXXXX",
          lat: "28.44491170883179",
          sexStr: "XXX",
        }
      ], // 数据
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    constructSource(projection) {
      var url = baseUrl + "?";
      var params = {
        VERSION: "1.0.0",
        LAYER: layerName,
        STYLE: style,
        TILEMATRIX: gridNames,
        TILEMATRIXSET: gridsetName,
        SERVICE: "WMS",
        FORMAT: format,
      };
      for (var param in params) {
        if (baseParams.indexOf(param.toUpperCase()) < 0) {
          url = url + param + "=" + params[param] + "&";
        }
      }
      url = url.slice(0, -1);
      var source = new WMTS({
        url: url,
        layer: params["LAYER"],
        matrixSet: params["TILEMATRIXSET"],
        format: params["FORMAT"],
        projection: projection,
        tileGrid: new WMTSTileGrid({
          tileSize: [256, 256],
          extent: [-180.0, -90.0, 180.0, 90.0],
          origin: [-180.0, 90.0],
          resolutions: resolutions,
          matrixIds: params["TILEMATRIX"],
        }),
        style: params["STYLE"],
        wrapX: true,
      });
      return source;
    },
    initMap() {
      var view;
      var projection = new Projection({
        code: "EPSG:4326", //SRS标识符代码,例如EPSG:4326。
        units: "degrees",
        // worldExtent:[108.991275931,28.43280519,109.003845419,28.447106813],// 地图最大最小经纬度
        global: false, // 该预测是否对整个地球有效。
        axisOrientation: "neu", // 获取此投影的轴方向。示例值包括:enu-默认的东,北,高程。neu-向北,向东,向上-对于“纬度/经度”地理坐标或朝南的横向墨卡托很有用。wnu-西,北,上-一些行星坐标系具有“西正”坐标系
      });
      view = new View({
        center: [108.9959979057312, 28.442698717117313],
        zoom: 18,
        minZoom: 14,
        maxZoom: 20,
        projection: projection, // 展示地图-
        extent: [108.991275931, 28.43280519, 109.003845419, 28.447106813],
      });
      this.map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: this.constructSource(projection),
          }),
        ],
        view: view,
        controls: defaults({
          attribution: false, //右下角的地图信息控件
          rotate: true, //指北针控件
          zoom: true, //缩放按钮控件
        }).extend([
          new FullScreen(), //全屏
          new ScaleLine(), //比例尺控件
          new ZoomSlider(), //缩放滚动条控件
          new MousePosition(), //鼠标拖动显示经纬度
        ]),
      });
      this.popup();
      this.addMaker();
    },
    //添加标注点
    addMaker() {
      // 清除上一次标注点
      this.layers.forEach((e) => {
        this.map.removeLayer(e);
      });
      //$("#patrol_number").text(this.dataList.length);
      this.dataList.forEach((obj) => {
        var vectorSource = new OlSourceVector({});
        //创建图标特性
        var iconFeature = new OlFeature({
          geometry: new OlGeomPoint([obj.lon, obj.lat], "XY"),
          name: "my Icon",
        });
        iconFeature.set("userId", obj.id);
        iconFeature.set("popuId", obj.popuId);
        iconFeature.set("username", obj.name);
        iconFeature.set("addTime", obj.residenceAddress);
        iconFeature.set("areaName", obj.areaName);
        iconFeature.set("sexStr", obj.sexStr);
        iconFeature.set("correctionTypeStr", obj.correctionTypeStr);
        iconFeature.set("personNumber", obj.personNumber);
        //将图标特性添加进矢量中
        vectorSource.addFeature(iconFeature);
        //创建图标样式
        var iconStyle = new OlStyleStyle({
          image: new OlStyleIcon({
            // opacity: 0.75,
            // scale:0.5,
            src: "/img/marker.png",
          }),
        });
        //创建矢量层
        var vectorLayer = new OlLayerVector({
          source: vectorSource,
          style: iconStyle,
        });
        this.layers.push(vectorLayer);
        //添加进map层
        this.map.addLayer(vectorLayer);
      });
    },
    popup() {
      //定位
      var container = document.getElementById("popup");
      var content = document.getElementById("popup-content");
      var popupCloser = document.getElementById("popup-closer");
      var overlay = new Overlay({
        //设置弹出框的容器
        element: container,
        //是否自动平移,即假如标记在屏幕边缘,弹出时自动平移地图使弹出框完全可见
        autoPan: true,
      });
      this.map.on("click", (e) => {
        //coodinate存放了点击时的坐标信息
        var coodinate = e.coordinate;
        //在点击时获取像素区域
        var pixel = this.map.getEventPixel(e.originalEvent);
        this.map.forEachFeatureAtPixel(pixel, (feature) => {
          //设置弹出框内容,可以HTML自定义
          var userId = feature.get("userId");
          var username = feature.get("username");
          var addTime = feature.get("addTime");
          var areaName = feature.get("areaName");
          var sexStr = feature.get("sexStr");
          var correctionTypeStr = feature.get("correctionTypeStr");
          //设置弹出框内容,可以HTML自定义
          var html = "";
          html += "<div><b>编号:</b>" + userId + "</div>";
          html +=
            '<div><b>姓名:</b><a οnclick="showFamilyInfo(' +
            feature.get("popuId") +
            ')">' +
            username +
            "</a></div>";
          html += "<div><b>性别:</b>" + sexStr + "</div>";
          html += "<div><b>矫正类别:</b>" + correctionTypeStr + "</div>";
          html += "<div><b>行政区域:</b>" + areaName + "</div>";
          html += "<div><b>地址:</b>" + addTime + "</div>";
          content.innerHTML = html;
          //设置overlay的显示位置
          overlay.setPosition(coodinate);
          //显示overlay
          this.map.addOverlay(overlay);
        });
        // 弹窗关闭按钮
        if (popupCloser) {
          popupCloser.addEventListener("click", () => {
            overlay.setPosition(undefined);
          });
        }
      });
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>

<style>
.el-font-size {
  font-size: 14px;
}
.ol-mouse-position {
  color: red;
  top: 13px;
  right: 60px;
}
.form-control {
  padding: 3px 12px !important;
}
.col-sm-8 label {
  padding-top: 7px;
}
p {
  margin: 0;
}
.active {
  background-color: #f5f5f5;
}

.ant-list * {
  outline: none;
}

.ant-avatar > img {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 5px;
}

.ant-list-item-meta-title > a {
  color: rgba(0, 0, 0, 0.65);
  -webkit-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

.form-control {
  padding: 15px 12px !important;
}

input,
select {
  border: 1px solid #e7eaec !important;
}

label {
  max-width: none;
}
.ol-popup {
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  position: absolute;
  background-color: #ffffff;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 10px;
  border-radius: 7px;
  bottom: 12px;
  left: -50px;
  min-width: 300px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: #eeeeee;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "✖";
  font-size: 11px;
}
</style>
2、点击地图定位并且获取经纬度
<template>
  <div class="" style="width:95%;height: 95%">
    <div style="width:100%;height: 100%" id="map" ref="rootmap"></div>
  </div>
</template>

<script>
    import "ol/ol.css";
    import { Map, View } from "ol";
    import {Tile as TileLayer} from 'ol/layer';
    import {WMTS} from 'ol/source';
    import WMTSTileGrid from 'ol/tilegrid/WMTS'
    import {Projection} from 'ol/proj';
    import {mapGetters} from "vuex";
    import FullScreen from 'ol/control/FullScreen';
    import ScaleLine from 'ol/control/ScaleLine';
    import ZoomSlider from 'ol/control/ZoomSlider';
    import MousePosition from 'ol/control/MousePosition';
    import { defaults } from "ol/control";
    // 图上图标相关
    import OlFeature from 'ol/Feature'
    import OlGeomPoint from 'ol/geom/Point'
    import OlLayerVector from 'ol/layer/Vector'
    import OlSourceVector from 'ol/source/Vector'
    import OlStyleStyle from 'ol/style/Style'
    import OlStyleIcon from 'ol/style/Icon'
    // 用来添加相关文字描述的
    // import Text from 'ol/style/Text'
    // import Fill from 'ol/style/Fill'
    const baseUrl = 'http://map.teacha.top/geoserver/gwc/service/wmts'
    const gridsetName = 'EPSG:4326'
    const gridNames = ['EPSG:4326:4','EPSG:4326:5','EPSG:4326:6','EPSG:4326:7','EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10', 'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19'] //切片名
    const style = ''
    const format = 'image/png'
    const layerName = 'xtmap:6-1'
    const resolutions = [0.0439453125,0.02197265625,
    0.010986328125, 0.0054931640625,0.00274658203125,0.001373291015625,
    6.866455078125E-4,3.433227539062E-4,1.716613769531E-4,8.58306884766E-5,
    4.29153442383E-5,2.14576721191E-5,1.07288360596E-5,5.3644180298E-6,
    2.6822090149E-6,1.3411045074E-6] //分辨率
    const baseParams = ['VERSION','LAYER','STYLE','TILEMATRIX','TILEMATRIXSET','SERVICE','FORMAT']
    //const map = []
    export default {
        name: "lq-map",
        data() {
            return {
                map: [],
                layers : []// 存放标注点。
            };
        },
        computed: {
            ...mapGetters(["userInfo"]),
        },
        methods: {
            constructSource(projection) {
                var url = baseUrl+'?'
                var params = {
                    'VERSION': '1.0.0',
                    'LAYER': layerName,
                    'STYLE': style,
                    'TILEMATRIX': gridNames,
                    'TILEMATRIXSET': gridsetName,
                    'SERVICE': 'WMS',
                    'FORMAT': format
                }
                for (var param in params) {
                    if (baseParams.indexOf(param.toUpperCase()) < 0) {
                        url = url + param + '=' + params[param] + '&';
                    }
                }
                url = url.slice(0, -1);
                var source = new WMTS({
                url: url,
                layer: params['LAYER'],
                matrixSet: params['TILEMATRIXSET'],
                format: params['FORMAT'],
                projection: projection,
                tileGrid: new WMTSTileGrid({
                    tileSize: [256,256],
                    extent: [-180.0,-90.0,180.0,90.0],
                    origin: [-180.0, 90.0],
                    resolutions: resolutions,
                    matrixIds: params['TILEMATRIX']
                }),
                style: params['STYLE'],
                wrapX: true
                });
                return source;
            },
            initMap() {
                 var view;
                 var projection = new Projection({
                    code: 'EPSG:4326', //SRS标识符代码,例如EPSG:4326。
                    units: 'degrees',
                    // worldExtent:[108.991275931,28.43280519,109.003845419,28.447106813],// 地图最大最小经纬度
                    global: false, // 该预测是否对整个地球有效。
                    axisOrientation: 'neu' // 获取此投影的轴方向。示例值包括:enu-默认的东,北,高程。neu-向北,向东,向上-对于“纬度/经度”地理坐标或朝南的横向墨卡托很有用。wnu-西,北,上-一些行星坐标系具有“西正”坐标系
                });
                view = new View({
                    center: [108.9959979057312, 28.442698717117313],
                    zoom: 18,
                    minZoom: 14,
                    maxZoom: 20,
                    projection: projection,// 展示地图-
                    extent: [108.991275931, 28.43280519, 109.003845419, 28.447106813],
                });
                this.map = new Map({
                    target: "map",
                    layers: [
                        new TileLayer({
                            source: this.constructSource(projection)
                        })
                    ],
                    view: view,
                    controls: defaults({
                        attribution: false,//右下角的地图信息控件
                        rotate: true,//指北针控件
                        zoom: true, //缩放按钮控件
                    }).extend([
                        new FullScreen(),//全屏
                        new ScaleLine(),//比例尺控件
                        new ZoomSlider(),//缩放滚动条控件
                        new MousePosition()//鼠标拖动显示经纬度
                        ]),
                });
                this.popup();
            },
            popup(){//定位
                this.map.on('click',(e)=>{
                    // 清除上一次标注点
                    this.layers.forEach(e => {
                      this.map.removeLayer(e);
                    })
                    var coodinate = e.coordinate;
                    // 清除上一次标注点
                    var vectorSource = new OlSourceVector({});
                    //创建图标特性
                    var iconFeature = new OlFeature({
                        geometry: new OlGeomPoint([coodinate[0],coodinate[1]], "XY"),
                        name: "my Icon"
                    });
                    //将图标特性添加进矢量中
                    vectorSource.addFeature(iconFeature);
                    //创建图标样式
                    var iconStyle = new OlStyleStyle({
                        image: new OlStyleIcon({
                            opacity: 0.75,
                            src: "/img/marker.png"
                        }),
                    });
                    //创建矢量层
                    var vectorLayer = new OlLayerVector({
                        source: vectorSource,
                        style: iconStyle
                    });
                    this.layers.push(vectorLayer);
                    //添加进map层
                    this.map.addLayer(vectorLayer);
                    this.$emit("onLonLat",coodinate[0],coodinate[1]);//获取到的经纬度。
                });
            }
        },
        mounted() {
            this.initMap()
        }
    };
</script>

<style>
  .el-font-size {
    font-size: 14px;
  }
  .ol-mouse-position{
    color: red;
    top: 13px;
    right: 60px;
  }
</style>


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值