openlayers 案例详细代码

<template>
    <el-container class = "index-container">
        <el-header>
            <Header
                :sys-data="headData.sysConfig"
                :search="headData.search"
                :bg-color="headData.bgColor"
                @select-change="selectChange"
                @freeSys="changeFreeSys"
            >
            </Header>
        </el-header>
        <el-main>
            <div id="map" class="map" style=" width: 100%;height: 100%; z-index: 1"></div>
            <!-- 地名、政区、批复列表 -->
            <left-list ref = "leftList"
                       v-show="treeVisable"
                       style="left:0px;top: 60px;position: fixed;" v-if="!freeOpen"></left-list>

            <!--自由图层列表-->
            <FreelyLeftList ref = "leftList"   style="left:0px;top: 60px;position: fixed;" :map.sync = "map" v-else @changeShowFreeRight="showFreeRight"></FreelyLeftList>

            <!-- 地名信息框 -->
            <PlaceInfo style="right:0px;top: 60px;position: fixed;text-align: left" v-show = "placeInfoShow" :show.sync = "placeInfoShow" ref = "placeInfo" :map.sync = "map" @clearFeature = "clearFeature" :draw.sync = "drawInstance" v-if="!freeOpen"></PlaceInfo>

            <!-- 自由图层信息框 -->
            <FreelyRIght :animateInterval.sync="animateInterval" style="right:0px;top: 60px;position: fixed" :map.sync = "map" v-show="showFreeRight" v-else></FreelyRIght>

            <!-- 政区信息框 -->
            <RegionInfo style="right:0px;top: 60px;position: fixed;text-align: left" v-show = "regionInfoShow" :show.sync = "regionInfoShow" ref = "regionInfo" v-if="!freeOpen"></RegionInfo>

            <!-- 工具条 -->
            <Control style="right:2%;top: 20%;position: fixed;text-align: left;" ref = "control" :map.sync = "map" :style = "placeInfoShow || regionInfoShow ? 'right: 20%' : ''" :draw-instance.sync = "drawInstance" :biaozhuVisable.sync = "biaozhuVisable" :mapVisable.sync = "mapVisable" :opacity.sync = "opacity" :diMingOpacity.sync = "diMingOpacity" v-if="!freeOpen"></Control>

            <!-- 自由图层工具条 -->
            <FreelyControl  ref = "control"  :map.sync = "map" :draw-instance.sync = "drawInstance" :mapVisable.sync = "mapVisable" :biaozhuVisable.sync = "biaozhuVisable" :opacity.sync = "opacity" :diMingOpacity.sync = "diMingOpacity"  v-else></FreelyControl>

            <!-- 地图层级 -->
            <div style="left:45%;top: 95%;position: fixed;text-align: left;z-index: 99999;color: var(--mainColor);" ref = "zoom">地图层级:{
   
   {zoom.toString().substring(0,zoom.toString())}}</div>
        </el-main>
    </el-container>
</template>

<script>
    import Map from 'ol/Map'
    import leftList from '@/views/list/index'
    import Header from '@/views/index/Header'
    import PlaceInfo from '@/views/component/info/PlaceInfo'
    import TileLayer from "ol/layer/Tile";
    import View from "ol/View";
    import {Vector as VectorLayer} from "ol/layer";
    import {Vector as VectorSource, XYZ} from "ol/source";
    import {Fill, Stroke, Style,Circle as StyleCircle} from "ol/style";
    import {WKT,GeoJSON} from "ol/format";
    import RegionInfo from '@/views/component/info/RegionInfo'
    import { getBottomLeft, getCenter, getForViewAndSize } from 'ol/extent'
    import ChangeUtil from '@/views/component/tools/ChangeUtil'
    import Control from '@/views/component/tools/Control'
    import Search from '@/views/index/Search'
    import DoubleClickZoom from 'ol/interaction/DoubleClickZoom'
    import Point from 'ol/geom/Point'
    import Polygon from 'ol/geom/Polygon'
    import LineString from 'ol/geom/LineString'
    import Icon from 'ol/style/Icon'
    import MultiPolygon from 'ol/geom/MultiPolygon'
    import MultiLineString from 'ol/geom/MultiLineString'
    import TileWMS from 'ol/source/TileWMS'
    import Image from 'ol/layer/Image'
    import ImageWMS from 'ol/source/ImageWMS'
    // 自由图层左侧列表
    import FreelyLeftList from '@/views/list/freelyIndex'
    // 自由图层右侧信息框
    import FreelyRIght from '@/views/component/info/freelyRightInfo.vue';
    // 自由图层右侧编辑栏
    import FreelyControl from '../component/tools/FreelyControl.vue'

    export default {
        name: 'Index',
        components: { Search, Control, ChangeUtil, RegionInfo, PlaceInfo, Header, leftList, FreelyLeftList, FreelyRIght, FreelyControl },
        data() {
            return {
                headData: {
                    sysConfig: {
                        title: '系统',
                        logo: require('../../assets/index/logo3.png'),
                        pinyin: 'SU ZHOU SHI QU HUA DI MING GUAN LI PING TAI',
                    },
                    search: '',
                    userInfo: {
                        userName: '111',
                        userHead: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
                    },
                    bgColor: 'background:#235298'
                },
                treeVisable: true,
                placeInfoShow: false,
                regionInfoShow: false,
                map : {},
                geomPoint : "鼠标单击地图获取坐标",
                mapUrl : 0,
                topSource : {},
                isGetPoint : null,
                searchShow : false,
                drawInstance : {},
                zoom : 9,
                mapVisable : "tianDiTu",// 底图切换
                opacity : 100,// 底图透明度
                diMingOpacity : 100,// 地名图层透明度
                mapCenter : [],
                presentWKT : "",
                colors : [
                    [255, 0, 0, 0.7],   // 红色
                    [255, 165, 0, 0.7], // 橙色
                    [255, 255, 0, 0.7], // 黄色
                    [0, 128, 0, 0.7],   // 绿色
                    [0, 0, 255, 0.7],   // 蓝色
                    [75, 0, 130, 0.7],  // 靛蓝色
                    [238, 130, 238, 0.7]  // 紫色
                ],
                lineLayer : {},//其他底图使用
                regionLayer: {},
                baiduLineLayer : {},//百度底图使用
                animateInterval : {},
                freeLineLayer: {},// 自由图层线
                freePointLayer: {},// 自由图层点
                freePolyonLayer: {},// 自由图层面
                showFreeRight: false,
                freeOpen: false, // 自由图层开关状态
                freelyRow: '',// 自由图层选中数据
                freeLayerId: '',// 自由图层id
                userData: {},
                tianDiTuBiaoZhu: null,// 天地图标注
                imageBiaoZhu: null,// 影像图标注
                biaozhuVisable: false, // 标注显示开关
            }
        },
        mounted() {
            this.initMap();
            this.addLayerAndListener();
            this.addPolygonLayer();
            this.userData = JSON.parse(localStorage.getItem('user'));
            // 事件总线监听值的变化
            this.$bus.$on('freelyRow', (data) => {
                this.freelyRow = data
                // console.log(data);
            })
            // 传左侧列表ID
            this.$bus.$on('freeValue', (data) => {
                this.freeLayerId = data.id
            })

        },
        // 改变自由图层右侧显示状态
        changeShowFreeRight(showFreeRight) {
            this.showFreeRight = showFreeRight
        },
        methods: {
            initMap() {
                var array = []
                array[0] = parseFloat(this.$common.mapCenterSetting[0].value.settingValue.split(",")[0])
                array[1] = parseFloat(this.$common.mapCenterSetting[0].value.settingValue.split(",")[1])
                this.mapCenter = array;
                console.log(this.mapCenter)
                var map = new Map({
                    // 设置地图图层
                    layers: [
                        new TileLayer({
                            name : "tianDiTu",
                            // source: new  OSM(), // 新建OSM数据,放置在图层
                            source: new XYZ({
                                url: "http://t7.tianditu.gov.cn/vec_w/wmts??SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=7f71befc1aca08b6f9a226c5eb1d4c5e",
                            }),
                            visible: true,
                            zIndex : 1,
                        }),
                        new TileLayer({
                            name : "image",
                            source: new XYZ({
                                url: "http://t3.tianditu.com/DataServer?T=img_w&tk=7f71befc1aca08b6f9a226c5eb1d4c5e&x={x}&y={y}&l={z}",
                            }),
                            visible: false,
                            zIndex : 1,
                        }),
                    ],
                    // 让id为map的div作为地图的容器
                    target: 'map',
                    // 设置显示地图的视图
                    view: new View({
                        // 定义地图显示中心于经度0度,纬度0度处
                        center: this.mapCenter,
                        // 义地图显示层级为2
                        zoom: 13,
                        projection: 'EPSG:4326',
                        maxZoom: 19,
                        minZoom: 1,
                    }),
                    controls: [
                    ],
                })
                map.getView().on('change:resolution', () => {
                    this.zoom = map.getView().getZoom();
                })
                // 删除默认的双击事件
                const dblClickInteraction = map
                    .getInteractions()
                    .getArray()
                    .find(interaction => {
                        return interaction instanceof DoubleClickZoom
                    })
                map.removeInteraction(dblClickInteraction)
                var overLayer = new VectorLayer({
                    title : "鼠标选中图层",
                    source : new VectorSource(),
                    style : new Style({
                        stroke: new Stroke({
                            color: 'rgba(102,6,6,0.7)',
                            width: 2
                        }),
                        fill : new Fill({
                            color : 'rgba(26,198,220,0.7)'
                        })
                    })
                });
                map.addLayer(overLayer);
                var vectorSource = new VectorSource();
                this.topSource = vectorSource;
                var polygon = new Style({
                    zIndex : 999999999,
                    stroke: new Stroke({
                        color: 'rgba(38,126,255,0.7)',
                        width: 2
                    }),
                    fill : new Fill({
                        color : 'rgba(26,198,220,0.7)'
                    })
                })
                var line = new Style({
                    zIndex : 999999999,
                    stroke: new Stroke({
                        color: 'rgba(38,126,255,0.7)',
                        width: 6
                    }),
                })
                var point = new Style({
                    zIndex : 999999999,
                    image: new Icon({
                        // radius: 5,//半径
                        // fill: new Fill({//填充样式
                        //     color: '#ff6688',
                        // }),
                        // stroke: new Stroke({//边界样式
                        //     color: '#555555',
                        //     width: 1
                        // })
                        src: require('../../assets/index/dingwei-tu.png'),
                    })
                })
                var topLayer = new VectorLayer({
                    title : "点面线图层",
                    source : vectorSource,
                    style : function (feature,resolution) {
                        if (feature.getGeometry() instanceof Point) {
                            return point;
                        }else if (feature.getGeometry() instanceof MultiPolygon || feature.getGeometry() instanceof Polygon){
                            return polygon;
                        }else if (feature.getGeometry() instanceof MultiLineString || feature.getGeometry() instanceof LineString) {
                            return line;
                        }
                    },
                    zIndex : 999999999,
                })
                map.addLayer(topLayer);
                var that = this;
                map.controls.remove();
                this.map = map;
                map.on('singleclick', function(e){
                    that.geomPoint = "POINT(" + e.coordinate[0] + " " + e.coordinate[1] + ")";
                    if (that.isGetPoint != null) {
                        document.getElementsByTagName("html")[0].style.cursor = "";
                        that.isGetPoint.setGeomPoint(that.geomPoint);
                    }
                })

            },
            overIcon(e,img){
                e.srcElement.children[0].children[0].src = require("../../assets/index/" + img + ".png");
            },
            leaveIcon(e,img){
                e.srcElement.children[0].children[0].src = require("../../assets/index/" + img + ".png");
            },
            moveMapCenterWithWKT(wkt){
                this.presentWKT = wkt;
                if (wkt != null && wkt != "" && wkt != 'null') {
                    var s = wkt;
                    var newfeature = new WKT().readGeometry(s,{
                        dataProjection : "EPSG:4326",
                        featureProjection : "EPSG:4326",
                    });
                    var that = this;
                    if (newfeature instanceof Point) {
                        this.map.getView().animate({ // 只设置需要的属性即可
                            center: getCenter(newfeature.getExtent()), // 中心点
                            zoom : 16,
                        })
                    }else {
                        this.map.getView().fit(newfeature.getExtent(),{
                            callback : function () {
                                that.map.getView().animate({ // 只设置需要的属性即可
                                    center: getCenter(newfeature.getExtent()), // 中心点
                                    zoom : that.map.getView().getZoom() - 1,
                                })
                            },
                            duration : 0,
                        });
                    }
                }
            },
            getGeomPoint(markInstance) {
                this.isGetPoint = markInstance;
                document.getElementsByTagName("html")[0].style.cursor = "url(\"https://road-resources.oss-cn-beijing.aliyuncs.com/7a321dc72c744b6cab52cba2f1b47431.png\"),default";
            },
            addFeatureToTopLayer(wkt,isMoveTo = true) {
                if (wkt == null || wkt == "") return;
                this.presentWKT = wkt;
                clearInterval(this.animateInterval);
                this.topSource.clear();
                var copyWkt = wkt + "";
                            // if (this.mapVisable == 'baiDu') {
                            //     wkt = WKTT.convert(gcoord.transform(WKTT.parse(wkt),gcoord.EPSG4326,gcoord.BD09))
                            // }
                    var readFeature = new WKT().readFeature((wkt),{
                        dataProjection : "EPSG:4326",
                        featureProjection : "EPSG:4326",
                    })
                    // 将id绑定到要素上 编辑时用 自由图层id
                    readFeature.set('signId', this.freeLayerId);
                    this.topSource.addFeature(readFeature);
                if (isMoveTo) {
                    this.moveMapCenterWithWKT(copyWkt);
                }
                var i = 0;
                var that = this;
                if (!(readFeature.values_.geometry instanceof Point)) {
                    this.animateInterval = setInterval(function() {
                        if (!that.freeOpen && that.$refs.placeInfo.editGeometry) return;
                        if (that.topSource.getFeatures().length == 0) {
                            return;
                        }
                        that.topSource.getFeatures()[0].setStyle(new Style({
                            stroke: new Stroke({
                                color: that.colors[i % that.colors.length],
                                width: 6
                            })
                        }));
                        i++;
                    }, 1000 / 3);
                }
            },
            clearFeature(num) {
                this.topSource.clear();
            },
            /**
             * 选择全文搜索输入框中的条目时触发此回调
             *
             * @param value 条目数据对应的ID
             */
            selectChange(value) {
                console.log('value = ', value)
                if (value != '') {
                    this.$refs.placeInfo.getInfo(value,(infoData) => {
                        if (infoData.placeName[0].geometry.value != null) {
                            this.addFeatureToTopLayer(infoData.placeName[0].geometry.value,true);
                        }
                    })
                }
            },
            //添加一个道路图层 和对应监听器
            addLayerAndListener(flag = true, show = true) {
                this.map.removeLayer(this.lineLayer);
                if(!show) return;
                var that = this;
                var source = new ImageWMS({
                    url: 'http://123.56.22.24:9823/geoserver/diming/wms',
                    params: {
                        FORMAT: "image/png",
                        VERSION: "1.1.1",
                        SRS: "EPSG:4326",
                        tiled: true,
                        LAYERS: "diming:341300_line",
                        TRANSPARENT : true,
                        STYLES : 'dm_line',
                        cql_filter : "code = '070501'"
                    },
                    serverType: "geoserver",
                    projection: "EPSG:4326",
                    crossOrigin: "Anonymous",
                    ratio: 1,
                });
                this.lineLayer = new Image({
                    projection: "EPSG:4326",
                    source: source,
                    type: "wms",
                    visible: true,
                    zIndex: 9998,
                })
                this.map.addLayer(this.lineLayer);
               if (flag && !that.freeOpen) {
                   this.$nextTick(() => {
                       this.map.on('click', function(evt) {
                           if (!that.freeOpen && that.$refs.placeInfo.editGeometry) return;
                           var viewResolution = (that.map.getView().getResolution());
                           var url = source.getFeatureInfoUrl(
                               evt.coordinate, viewResolution, 'EPSG:4326',
                               {'INFO_FORMAT': 'application/json'});
                           if (url) {
                               fetch(url)
                                   .then(function (response) { return response.text(); })
                                   .then(function (html) {
                                       if (JSON.parse(html).features.length == 0) {
                                           that.presentWKT = "";
                                           that.clearFeature();
                                           return;
                                       }
                                       that.$refs.placeInfo.getInfo(JSON.parse(html).features[0].properties.id);
                                       //覆盖一个元素在上方
                                       const geoJsonFormat = new GeoJSON();
                                       const olGeom = geoJsonFormat.readGeometry(JSON.parse(html).features[0].geometry);
                                       that.addFeatureToTopLayer(new WKT().writeGeometry(olGeom),false);
                                   });
                           }
                       });
                   })
               }
            },
            addPolygonLayer(show = true) {
                this.map.removeLayer(this.regionLayer);
                if(!show) return;
                this.regionLayer = new TileLayer({
                    source: new TileWMS({
                        url: 'http://123.56.22.24:9823/geoserver/diming/wms',
                        params: {
                            'LAYERS': 'diming:341300_ploygon',
                            FORMAT: "image/png",
                            VERSION: "1.1.1",
                            SRS: "EPSG:4326",
                            tiled: true,
                            TRANSPARENT : true,
                            STYLES : 'dm_polygon',
                        },
                        serverType: 'geoserver',
                    }),
                    zIndex : 9999,
                });

                this.map.addLayer(this.regionLayer);

            },

            // 渲染自由图层
            addFreeLayers(show = false){
                this.map.removeLayer(this.freeLineLayer);
                this.map.removeLayer(this.freePolyonLayer);
                this.map.removeLayer(this.freePointLayer);
                if(!show) return;
                var that = this;
                this.freePointLayer = new Image({
                    source: new ImageWMS({
                        url: 'http://123.56.22.24:9823/geoserver/diming/wms',
                        params: {
                            LAYERS: 'diming:341300_suzhou_free_point',
                            FORMAT: 'image/png',
                            VERSION: '1.1.0',
                            TRANSPARENT: true,
                            VIEWPARAMS: 'user:' + this.userData.id
                        },
                        serverType: 'geoserver',
                    }),
                    zIndex : 9999,
                });

                this.freeLineLayer = new Image({
                    source: new ImageWMS({
                        url: 'http://123.56.22.24:9823/geoserver/diming/wms',
                        params: {
                            LAYERS: 'diming:341300_suzhou_free_line',
                            FORMAT: 'image/png',
                            VERSION: '1.1.0',
                            TRANSPARENT: true,
                            VIEWPARAMS: 'user:' + this.userData.id
                        },
                        serverType: 'geoserver',
                    }),
                    zIndex : 9999,
                });

                this.freePolyonLayer = new Image({
                    source: new ImageWMS({
                        url: 'http://123.56.22.24:9823/geoserver/diming/wms',
                        params: {
                            LAYERS: 'diming:341300_suzhou_free_polygon',
                            FORMAT: 'image/png',
                            VERSION: '1.1.0',
                            TRANSPARENT: true,
                            VIEWPARAMS: 'user:' + this.userData.id
                        },
                        serverType: 'geoserver',
                    }),
                    zIndex : 9999,
                });
                this.map.addLayer(this.freeLineLayer);
                this.map.addLayer(this.freePolyonLayer);
                this.map.addLayer(this.freePointLayer);
            },
            // 自由图层打开、关闭 地图、图层加载改变
            changeFreeSys(val){
                this.freeOpen = val;
                if(val){
                    this.mapVisable = 'image'
                    this.addLayerAndListener(true,false)
                    this.addPolygonLayer(false)
                    this.addFreeLayers(true)
                }
                else{
                    this.mapVisable = 'tianDiTu'
                    this.addLayerAndListener(true,true)
                    this.addPolygonLayer(true)
                    this.addFreeLayers(false)
                }
            },

        },
        watch : {
            placeInfoShow(newVal, oldVal) {
                this.regionInfoShow = false;
            },
            mapVisable(newVal, oldVal) {
                console.log(newVal, 'map')
                this.map
                    .getLayers()
                    .getArray()
                    .forEach((layer) => {
                        if (layer.get("name") != undefined) {
                            if (layer.get("name") == newVal) {
                                layer.setVisible(true);
                            } else {
                                layer.setVisible(false);
                            }
                        }
                    });
                if (this.presentWKT != "") {
                    this.addFeatureToTopLayer(this.presentWKT);
                }
            },
            opacity(newVal, oldVal) {
                console.log(newVal, oldVal);
                this.map
                    .getLayers()
                    .getArray()
                    .forEach((layer) => {
                        console.log(layer.get("name"))
                        if (layer.get("name") != undefined) {
                            layer.setOpacity(newVal / 100);
                        }
                    });
            },
            diMingOpacity(newVal, oldVal) {
                this.map
                    .getLayers()
                    .getArray()
                    .forEach((layer) => {
                        if (layer.get("name") == undefined) {
                            layer.setOpacity(newVal / 100);
                        }
                    });
            },
            freelyRow: function(wkt) {
                this.addFeatureToTopLayer(wkt)
            },
            biaozhuVisable(newVal, oldVal) {
                console.log(newVal,111)
                this.map.removeLayer(this.imageBiaoZhu);
                this.map.removeLayer(this.tianDiTuBiaoZhu);
                if (this.mapVisable == 'image' && newVal) {
                    this.imageBiaoZhu = new TileLayer({
                        source: new XYZ({
                            url: "http://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=7f71befc1aca08b6f9a226c5eb1d4c5e",
                        }),
                        visible: true,
                        zIndex: 2,
                    });
                    // 将影响图标注添加进地图
                    this.map.addLayer(this.imageBiaoZhu);
                } else if (this.mapVisable == 'tianDiTu' && newVal) {
                    this.tianDiTuBiaoZhu = new TileLayer({
                        source: new XYZ({
                            url: "http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=7f71befc1aca08b6f9a226c5eb1d4c5e",
                        }),
                        visible: true,
                        zIndex: 2,
                    });
                    this.map.addLayer(this.tianDiTuBiaoZhu);
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
    *{
        margin: 0;
        padding: 0;
    }
    .el-container {
        height: 100%;
    }
    .el-main {
        background-color: #E9EEF3;
        color: #333;
        text-align: center;
        height: 100%;
        width: 100%;
    }
    .el-row {
        height: 100%;
    }
    .el-col {
        height: 100%;
    }
    h4 {
        width:212px;
        font-family:Source Han Sans CN;
        font-size:19px;
        height: 30px;
        color:#fff;
        line-height:19px;
        opacity:1;
        display: inline;
        float: top;
        position: absolute;
        margin-top: 0.8%;
    }

    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background:#235298;
        border:1px solid #cfd0d8;
    }

</style>

猜你喜欢

转载自blog.csdn.net/m0_65607651/article/details/133919937