博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue+pg库+openlayer5+geoserver+离线地图瓦片构建gis地图+地图撒点+点击点出现地图弹框(***完整流程***)
阅读量:3909 次
发布时间:2019-05-23

本文共 21690 字,大约阅读时间需要 72 分钟。

实现效果:(ol5的api)

一、在vue项目中使用gis地图,实现地图的搭建

    1、在pg库中存入你的gis地图数据(这里数据不提供,默认是实现了这一步)

    2、在geoserver中获取pg库中的数据,并在geoserver中发布图层,将数据库中的数据发布成我们可以使用的地图

         ( 如果对这个步骤都不了解的朋友可以看下这个 ,详细步骤:)

    3、在tomcate中放入地图瓦片

    4、在页面引用efgis.js:

efgis.js ,公共ol5方法封装

import {Map, View, Overlay } from 'ol';import Feature from 'ol/Feature';import {Text, Fill, Stroke, Style, Icon, Circle} from 'ol/style';import {Tile as TileLayer, Vector as VectorLayer,} from 'ol/layer';import {Vector as VectorSource, XYZ, TileWMS} from 'ol/source';import {LineString, Point,Circle as CircleL} from 'ol/geom';import {Control} from 'ol/control';import axios from 'axios';import store from '@/store/store.js';// 设置常量var efgis = {};const devStr = 'xinxing';/** * 地址 */const DataSource = 'EPSG:4326';    //坐标系var ServiceIP = '';               //地图服务地址var TomcatIP = '';                //瓦片服务地址var MapUrl = '';                 //geoserver服务地址var MapJDUrl = '';               //瓦片地址const defaultDatas = {  center: [112.16629, 22.63025],  zoom: 11,  minZoom: 11,  maxZoom: 24};var geolayerName = 'xinxing_xian';var nowName = '';var nowCenter = '';var nowZoom = '';var map = null;var points = [];// 图层变量let JDLayer = null;let xinxingWhitelayer = null;let nowIon = '';let nowLat = '';efgis = {  /*  * 初始化地图对象  * */  init: function (mapDom,type) {    /**     * 填充地址-start     */    ServiceIP = store.state.ServiceIP;//地图服务地址    TomcatIP = store.state.TomcatIP; //瓦片服务地址    MapUrl = ServiceIP + 'geoserver/xinxing/wms';//geoserver服务地址    MapJDUrl =  TomcatIP + 'xinxingmap/roadmap/{z}/{x}/{y}.png';//瓦片地址     /**     * 填充地址-end     */    if(type !=undefined){      if(type.name != undefined){        nowName = type.name      }      if(type.center != undefined){        nowCenter = type.center      }      if(type.zoom != undefined){        nowZoom = type.zoom      }    }else{      nowName = geolayerName      nowCenter = defaultDatas.center      nowZoom = defaultDatas.zoom    }    map = new Map({      target: mapDom,      view: new View({        center: nowCenter,        zoom: nowZoom,        projection: DataSource,      //默认的是 'EPSG:3857'横轴墨卡托投影        minZoom: defaultDatas.minZoom,        maxZoom: defaultDatas.maxZoom      }),      layers: [],      control: new Control({        zoom: false      })    });    this.initEvent();    this.addGeoLayer(nowName);    return map;  }, /** *  给地图添加事件 */  initEvent() {    var that = this;    // 点击事件    map.on('singleclick', e => {//点击事件获取当前经纬度      nowIon = e.coordinate[0];//当前鼠标点击的经度      nowLat = e.coordinate[1];//当前鼠标点击的纬度      console.log('经度'+nowIon+","+'纬度'+nowLat);    })    //监听鼠标滚动事件    map.getView().on('change:resolution', e => {      let currentZoom = map.getView().getZoom();//当前地图层级      if (currentZoom >= 13) {        that.addXYZLayer();//当层级超过13层时调动地图瓦片        that.addXinXingWhite();//当层级超过13层时调动geoserver图层      } else {        that.removeXYZLayer();        that.removeXinXingWhite();      }    });    let popupDom = document.getElementById('mapPopup');    let popupContent = document.getElementById('popupContent');    var overlay = new Overlay({      element: popupDom,      autoPan: true,      autoPanAnimation: {        duration: 250      }    });    // 点击事件    map.on("click", evt => {      let addPopup = function (data) {        if (data == undefined) {          return;        }        let html = "";        let html2 = '';        for (let i in data) {          if (data[i].name == 'name') {            html += `

${data[i].val}

` continue; } html2 += `

${data[i].name}:${data[i].val}

` } ; return html + html2; } let flag = false; let pixel = map.getEventPixel(evt.originalEvent); map.forEachFeatureAtPixel(pixel, (feature) => { var baseURL = store.state.baseUrl; // console.log(111,feature.get('geometry').getType()) if (feature.get('geometry').getType() != 'Point') { return; } // console.log(222,feature.getProperties()) if (feature != undefined) { let properties = feature.getProperties(); var coordinate = evt.coordinate; if (properties.html == '' || properties.html == undefined) { let data = properties.data; let html = addPopup(data); if (html != '') { $(popupContent).html(html) overlay.setPosition(coordinate); flag = true; } }else { //供电服务-停电管理-地图弹框 if(properties.html.class =='gdfw_tdgl' && properties.html.id !='' && properties.html.id !=undefined && properties.html.id !=null){ let url = `${baseURL}:9004/tdfw/findGzMessage`; let param = new URLSearchParams(); param.append("id", properties.html.id); param.append("bs", properties.html.bs); param.append("dj", properties.html.dj); // axios({ // url: url, // method: 'post', // params: param // }).then((res) => { // if (res.status === 200) { let res = { data:{ gdxx:{ lxdh:"18610086001", qxsj:"2019-07-10 09:50:00", qxzt:"处理完成", gzdz:"估伦村公用台变(200kVA)", gzfzr:"张三", gznr:"10kV长江线703开关保护测控装置零序过流保护功能调试和零序CT变比测试", gzzt:[ { sj:"2019-07-10 08:30:00", zt:"派单" }, { sj:"2019-07-10 08:50:00", zt:"接单" }, { sj:"2019-07-10 09:50:00", zt:"到达现场" }, { sj:"2019-07-10 10:30:00", zt:"故障确认" }, { sj:"2019-07-10 12:22:00", zt:"处理完成" } ] }, xyfw:{ tdsb:"1、35kV蕉山变电站10kV太平线#51杆51T1开关后段线路;2、110kV六祖变电站701开关;3、110kV六祖变电站702开关。", xlmc:"蕉山线", yxdkh:"否", yxgl:"否", yxzykh:"否" } } } let gdxx = res.data.gdxx; let xyfw = res.data.xyfw; let gzttStr = '
' gdxx.gzzt.forEach((item)=>{ let nowLi = `
  • `+item.zt+`

    `+item.sj+`
  • ` gzttStr += nowLi; }); let str = `
    • 工单信息
    • 影响范围
    • 工作负责人:`+gdxx.gzfzr+`

      联系电话:`+gdxx.lxdh+`

    • 抢修状态:`+gdxx.qxzt+`

      抢修时间:`+gdxx.qxsj+`

    • 故障地址:`+gdxx.gzdz+`

    • 故障描述:`+gdxx.gznr+`

    • 工作状态:

        `+gzttStr+`
    ` $(popupContent).html(str) overlay.setPosition(coordinate); flag = true; return; // } // }).catch((error) => { // console.log(error); // }) } let data = properties.html; let html = data; if (html != '') { $(popupContent).html(html) overlay.setPosition(coordinate); flag = true; } } } }) if (flag) { map.addOverlay(overlay) } else { map.removeOverlay(overlay); } }); }, //添加geoserver图层方法 addGeoLayer: function (name,zIndex) { let layer = new TileLayer({ source: new TileWMS({ url: MapUrl, params: { 'LAYERS': devStr + ':' + name, 'TILED': true }, serverType: 'geoserver', projection: DataSource }), zIndex: zIndex?zIndex:10 }); map.addLayer(layer); return layer }, // 添加geoserver图层 addXinXingWhite: function () { if(xinxingWhitelayer==null){ // console.log(1111) xinxingWhitelayer = this.addGeoLayer("xinxing_yaogan", 14); // console.log(222,xinxingWhitelayer) } }, // 移除geoserver图层 removeXinXingWhite:function(){ if(xinxingWhitelayer!=null){ map.removeLayer(xinxingWhitelayer); xinxingWhitelayer = null; } }, /* * 添加瓦片图层 * */ addXYZLayer: function () { if (JDLayer) { return; } else { JDLayer = new TileLayer({ source: new XYZ({ url: MapJDUrl }), zIndex: 11 }); map.addLayer(JDLayer); } }, // 删除瓦片图层 removeXYZLayer: function () { if (JDLayer) { map.removeLayer(JDLayer) JDLayer = null; } }, // 添加多个点,返回图层对象Feature addPointsLayer: function (points) { let arrLayer = []; for (let i = 0; i < points.length; i++) { let point1X = points[i].lon; let point1Y = points[i].lat; let name1 = points[i].num; let feature = this.vectorPointCircleReturn([point1X, point1Y], name1, points[i]) arrLayer.push(feature) } return arrLayer; }, addPointsLayer_zygk: function (points) { let arrLayer = []; for (let i = 0; i < points.length; i++) { let pointX = points[i].lon; let pointY = points[i].lat; let name = points[i].name; let img = points[i].img; let params = points[i].params let option ={ coordinate:[pointX, pointY], img:img, name:name, params: params, scale:1.2, zIndex:99 } if (points[i].html != undefined) { option.html = points[i].html } else { option.html = "" } let feature = this.vectorPointImgReturn_zygk(option) arrLayer.push(feature) } return arrLayer; }, //删除多个点,输入图层对象数组 removePointslayer(arr) { for (let i = 0; i < arr.length; i++) { map.removeLayer(arr[i]); } }, // 撒点,点是图片 vectorPointImg: function (point, img, name) { let scale = 0.4; let styleFunc = function () { let style = new Style({ image: new Icon({ src: require('../assets/images/mapIcon/' + img + '.png'), scale: scale }), text: new Text({ //文本样式 text: name, textAlign: 'center', offsetY: -20, offsetX: 10, textBaseline: 'middle', font: '17px Calibri,sans-serif', fill: new Fill({ color: '#cd5c5c' }) }) }) return style; } let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 99, style: styleFunc() }); // let points = [112.16629, 22.65025] // let points = fromLonLat([112.16629, 22.65025]) let fetureLine = new Feature({ geometry: new Point(point) }); source.addFeature(fetureLine); map.addLayer(vector); }, vectorPointCircleReturn: function (point, name, data) { let scale = 0.4; let styleFunc = function () { let style = new Style({ image: new Circle({ radius: 7, stroke: new Stroke({ color: '#cd5c5c' }), fill: new Fill({ color: '#cd5c5c' }) }), text: new Text({ //文本样式 text: data.name ? data.name : '', textAlign: 'center', offsetY: -20, offsetX: 10, textBaseline: 'middle', font: '17px Calibri,sans-serif', fill: new Fill({ color: '#cd5c5c' }) }) }) return style; } let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 99, style: styleFunc() }); // let points = [112.16629, 22.65025] // let points = fromLonLat([112.16629, 22.65025]) let fetureLine = new Feature({ geometry: new Point(point), data: data.params }); source.addFeature(fetureLine); map.addLayer(vector); return vector; }, vectorPointImgReturn_zygk: function (option) { let styleFunc = function () { let scale = 0.4; let zIndex=99; let style = new Style({ image: new Icon({ src: require('../assets/images/mapIcon/' + option.img + '.png'), scale: option.scale?option.scale:scale }), text: new Text({ //文本样式 text: option.name?option.name:'', textAlign: 'center', offsetY: -20, offsetX: 10, textBaseline: 'middle', font: '17px Calibri,sans-serif', fill: new Fill({ color: '#cd5c5c' }) }) }) return style; } let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: option.zIndex?option.zIndex:zIndex, style: styleFunc() }); // let points = [112.16629, 22.65025] // let points = fromLonLat([112.16629, 22.65025]) let fetureLine = new Feature({ geometry: new Point(option.coordinate), data: option.params, html: option.html }); source.addFeature(fetureLine); map.addLayer(vector); return vector; }, // 撒点,可以改变样式 vectorPointColor: function (coordinate, styles, data) { let defaultStyle = { color: '#cd5c5c', radius: 7, text: '' } let styleFunc = function (styles) { let style = new Style({ image: new Circle({ radius: styles.radius ? styles.radius : defaultStyle.radius, stroke: new Stroke({ color: styles.color ? styles.color : defaultStyle.color }), fill: new Fill({ color: styles.color ? styles.color : defaultStyle.color }) }), text: new Text({ //文本样式 text: styles.text ? styles.text : defaultStyle.text, textAlign: 'center', offsetY: -20, offsetX: 0, textBaseline: 'middle', font: '16px Microsoft YaHei', fill: new Fill({ color: styles.color ? styles.color : defaultStyle.color }) }) }) return style; } let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 99, style: styleFunc(styles) }); // let points = [112.16629, 22.65025] // let points = fromLonLat([112.16629, 22.65025]) let feturePoint = new Feature({ geometry: new Point(coordinate), data: data.params }); source.addFeature(feturePoint); map.addLayer(vector); return vector; }, // 潮流线路绘制 vectorLineAutoDash_clt: function (lineArr) { let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 97 }); // 遍历画线画点 for (let j = 0; j < lineArr.length; j++) { let lines = lineArr[j]; for (let i = 0; i < lines.length; i++) { if (i == lines.length - 1) { continue; } let to = { coordinate: [lines[i].lon, lines[i].lat], name: lines[i].name, type: lines[i].type, params: lines[i].params, }; let from = { coordinate: [lines[i + 1].lon, lines[i + 1].lat], name: lines[i + 1].name, type: lines[i + 1].type, params: lines[i + 1].params, } let points = new Array(to.coordinate, from.coordinate); // let defaultStyle = { // color:'#cd5c5c', // radius :7, // text:'' // } // 设置变电站点的颜色 let getColor = function (type) { if (type == '110') { return '#cd5c5c' } else if (type == '35') { return '#33cccc' } else if (type == '220') { return '#fff'; } else { return '#fff'; } } let colorLine = getColor(to.type) // 绘制点 this.vectorPointColor(from.coordinate, { color: getColor(from.type), radius: 7, text: from.name, }, from) this.vectorPointColor(to.coordinate, { color: getColor(to.type), radius: 7, text: to.name }, to) let fetureLine = new Feature({ geometry: new LineString(points), dashOffset: 0 }); // 线背景 let outlineStroke = new Style({ stroke: new Stroke({ // color:'red', // width:5 }) }); let getAnimationStrokeStyle = function () { return new Style({ stroke: new Stroke({ color: colorLine, width: 4, lineDash: [1, 3, 5], lineDashOffset: fetureLine.get("dashOffset") }) }) }; let getStyle = function () { return [outlineStroke, getAnimationStrokeStyle()]; } fetureLine.setStyle(getStyle); source.addFeature(fetureLine); setInterval(function () { let offset = fetureLine.get('dashOffset'); offset = offset == 8 ? 0 : offset + 4; fetureLine.set('dashOffset', offset); }, 100); } } map.addLayer(vector); }, // 画直线,可以改变颜色 vectorLineSoildColor: function (points, color) { let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 99 }); let fetureLine = new Feature({ geometry: new LineString(points), }); let defaultStyle = { color: 'yellow' } function getStyle(color) { return new Style({ stroke: new Stroke({ color: color == '' ? defaultStyle.color : color, width: 5 }) }); } fetureLine.setStyle(getStyle(color)); source.addFeature(fetureLine); map.addLayer(vector); }, // 画多条直线 vectorLinesSoild: function (points) { let isError = false; for (let i = 0; i < points.length; i++) { if (i == (points.length - 1)) return; let point1X = points[i].lon; let point1Y = points[i].lat; let point2X = points[i + 1].lon; let point2Y = points[i + 1].lat; let color = ''; if (points[i].yc == 1) { if (!isError) { color = 'red'; } isError = !isError; } this.vectorLineSoildColor(new Array([point1X, point1Y], [point2X, point2Y]), color); } }, // 恢复默认位置 resetCenter: function () { map.getView().animate({center: defaultDatas.center}, {zoom: defaultDatas.zoom}) }, // 根据zoom加载或者删除点 LineAndPoindZoom: function (points) { let xlPoints = []; let isOk = true; map.on('moveend', e => { let currentZoom = map.getView().getZoom(); if (currentZoom >= 13) { if (isOk) { xlPoints = this.addPointsLayer(points) isOk = !isOk; } } else { if (!isOk) { this.removePointslayer(xlPoints) xlPoints = []; isOk = !isOk; } } }); }, load3minReset: function () { let that = this; let zoomArr = []; let i = 0; let timer = setInterval(() => { let zoom = map.getView().getZoom(); if (i == 29) { that.resetCenter(); zoomArr = []; i = 0; window.clearInterval(timer); return; } i++; if (zoomArr.length > 0) { if (zoomArr[zoomArr.length - 1] != zoom) { zoomArr = []; i = 0; return; } } zoomArr.push(zoom); }, 6000) return timer; }, addCirclelayers:function (data,r) { // let data = [112.314079,22.6958978]; r = r/10000; let styleFunc = function (name) { let style = new Style({ fill:new Fill({ color:[255,0,0,.3] }), stroke:new Stroke({ color:'red', width:2 }) }) return style; } let source = new VectorSource({ wrapX: false }); let vector = new VectorLayer({ source: source, zIndex: 99, style: styleFunc(name) }); // let points = [112.16629, 22.65025] // let points = fromLonLat([112.16629, 22.65025]) let fetureLine = new Feature({ // geometry: new CircleL(data,0.005), geometry: new CircleL(data,r), }); source.addFeature(fetureLine); map.addLayer(vector); }}export default efgis

          5、创建地图组件 power_tqT.vue ,并引用

         6、地图弹框的组件mapPopup.vue

    ***注意这是我的项目必须的组件,方法,请谨慎使用,基于openlayer5实现的gis地图,有不懂的可以一起讨论

    转载地址:http://eawrn.baihongyu.com/

    你可能感兴趣的文章
    一套标准的ASP.NET Core容器化应用日志收集分析方案
    查看>>
    如何使用 C# 扩展方法
    查看>>
    C#如何回到主线程,如何在委托指定线程执行
    查看>>
    服务器重新部署踩坑记
    查看>>
    .NET应用程序安全操作概述
    查看>>
    C# WPF:把文件给我拖进来!!!
    查看>>
    .NET5发布了,腾讯招聘点名要求精通MySQL,而不是SQLServer!
    查看>>
    让 CefSharp.WinForms 应用程序同时支持32位(x86)和64位(x64)的解决方案
    查看>>
    Docker Vs Podman
    查看>>
    程序员过关斩将--论系统设计的高可扩展性
    查看>>
    如何在 Asp.Net Core MVC 中处理 null 值
    查看>>
    浅谈AsyncLocal,我们应该知道的那些事儿
    查看>>
    移动建模平台元数据存储架构演进
    查看>>
    Visual Studio 即时窗口实用技巧
    查看>>
    如何在 C# 中使用 Dapper ORM
    查看>>
    AgileConfig-轻量级配置中心 1.1.0 发布,支持应用间配置继承
    查看>>
    C# :异步编程的注意点
    查看>>
    Dotnet Core下的Channel, 你用了吗?
    查看>>
    ASP.NET Core 5.0新增功能摘要
    查看>>
    回顾 | 进击吧! Blazor!系列
    查看>>