• ol(openlayers)使用记录


    1. 项目环境:vue3+ts+vite
    2. ol版本:7.1.0
    3. 安装:
      yarn add ol或者npm i ol
    4. 使用:保护区和标记点
    	<template>
      <div id="map" class="my_map">
        <div>我在地域div>
      div>
    template>
    
    <script lang="ts" setup>
    import { onMounted, reactive, shallowRef } from "vue";
    
    import "ol/ol.css"; // 样式
    import { Map, View, Feature } from "ol";
    import TileLayer from "ol/layer/Tile";
    import VectorSource from "ol/source/Vector.js";
    import VectorLayer from "ol/layer/Vector.js";
    import { XYZ, Cluster } from "ol/source";
    import { defaults, ZoomSlider, Attribution, ScaleLine, FullScreen } from "ol/control";
    import { Point, Polygon, MultiPolygon } from "ol/geom";
    import { Style, Icon, Fill, Stroke, Text } from "ol/style";
    
    import { getArea } from "@/api/species";
    import { useRouter } from "vue-router";
    import polygonData from '@/utils/feature.json'
    
    const map = shallowRef(); // 存放地图实例
    const router = useRouter();
    const state = reactive({
      loading: false,
      name: '',
      mapData: [] as any[]
    })
    
    // 区域默认样式
    let defaultStyle = new Style({
      fill: new Fill({
        color: "#16a08580"
      }),
      stroke: new Stroke({
        width: 2,
        color: '#16a085'
      })
    })
    
    // 区域高亮样式
    let hightStyle = new Style({
      fill: new Fill({
        color: "#40e0d080"
      }),
      stroke: new Stroke({
        width: 2,
        color: '#40e0d0'
      })
    })
    
    let highlight: any; // 设置高亮元素变量
    onMounted(() => {
      state.name = router.currentRoute.value.query.name as string || '';
      initMap()
      // onLoad()
      addArea(polygonData.features)
    
      addMarker([[101.501624, 24.966174], [101.501624, 24.966265], [101.501624, 21.966456], [101.501624, 24.116447], [101.501624, 24.966438], [101.501624, 24.966429], [101.501624, 24.966414]])
    })
    
    // 实例化地图
    function initMap() {
      // 清除地图节点中的其他元素
      let map_dom = document.querySelector(".my_map");
      if (map_dom && map_dom.children[0]) {
        map_dom!.removeChild(map_dom!.children[0]);
      }
      // 地图实例
      map.value = new Map({
        target: "map", // 挂载元素id
        // 设置地图图层
        layers: [
          new TileLayer({
            source: new XYZ({
              url: "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key",
            }),
          }), // 天地图瓦片底图
          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=你的key",
            }),
          }), // 天地图标注
        ],
        // 设置显示地图的视图
        view: new View({
          // 设置地图中心范围
          projection: "EPSG:4326", //EPSG:3857坐标系(投影坐标) EPSG:4326 坐标系(地理坐标)
          center: [101.501624, 24.966424], // 定义地图显示中心于经度,纬度
          zoom: 5, // 缩放级别
          maxZoom: 19, // 最大缩放级别
          minZoom: 1, // 最小缩放级别
          constrainResolution: true, //自动缩放到距离最近的整数级,非整数级别时地图会糊
          smoothResolutionConstraint: false, //2.关闭无级缩放地图
        }),
        //设置地图控件
        controls: defaults().extend([
          new ZoomSlider(), // 缩放按钮
          new Attribution(), // 版权信息
          new ScaleLine(), // 比例尺
          new FullScreen(), // 全屏控件
        ]),
      });
    
    
    }
    
    /**
     * 设置区域
     */
    function addArea(geo: any[]) {
      if (geo.length == 0) return false;
      let areaFeature = null as any;
      // 设置图层
      let areaLayer = new VectorLayer({
        style: defaultStyle, // 默认样式
        source: new VectorSource({
          features: []
        })
      });
      // 添加图层
      map.value.addLayer(areaLayer);
      geo.forEach((item: any) => {
        if (item.geometry.type == "MultiPolygon") {
          areaFeature = new Feature({
            properties: item.properties,
            geometry: new MultiPolygon(
              item.geometry.coordinates
            )
          });
        } else if (item.geometry.type == "Polygon") {
          areaFeature = new Feature({
            properties: item.properties,
            geometry: new Polygon(
              item.geometry.coordinates
            )
          });
        }
        areaLayer!.getSource()!.addFeatures([areaFeature]);
      });
      //悬浮切换图层颜色
      map.value.on("pointermove", function (evt: any) {
        // 是否是拖拽事件
        if (evt.dragging) {
          return;
        }
        let feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature: any) {
          return feature;
        });
    
        // 是否规划区域
        if (feature && (feature.getGeometry() instanceof Polygon || feature.getGeometry() instanceof MultiPolygon)) {
          map.value.getTargetElement().style.cursor = "pointer"
          if (highlight) {
            highlight.setStyle(defaultStyle)
          }
          highlight = feature;
          feature.setStyle(hightStyle)
        } else {
          map.value.getTargetElement().style.cursor = ""
          if (highlight) {
            highlight.setStyle(defaultStyle)
          }
        }
      });
    
      //单机图层
      map.value.on("singleclick", function (evt: any) {
        // 判断点击的坐标是否在保护区范围内
        let feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature: any) {
          return feature;
        });
        if (feature != null) {
          let properties = feature.get("properties");
          console.log(feature.getGeometry(), properties); //{"name": "高黎贡山","ID": 95, "Area": 4800000000,"sheng": ""}
          // todo 点击事件
        }
      });
    }
    
    
    //添加标记点
    function addMarker(lnglat: any, options = {}) {
      const lnglats = lnglat;
      // 创建Feature对象集合
      const features = [];
      for (let i = 0; i < lnglats.length; i++) {
        if (lnglats[i][0] !== '' && lnglats[i][1] !== '') {
          const numAry = new Feature({
            properties: {
              name: 'dsfsasadf'
            },
            geometry: new Point([parseFloat(lnglats[i][0]), parseFloat(lnglats[i][1])]),
          });
          features.push(numAry);
        }
      }
    
      const clusterSource = new Cluster({
        distance: 0.1, //标注之间
        source: new VectorSource({
          features: features,
        }),
      });
    
      const iconStyle = new Style({
        image: new Icon({
          opacity: 1,
          src: 'https://cdn-icons-png.flaticon.com/512/1483/1483336.png',
          anchor: [0.5, 3], // 偏移位置
          anchorOrigin: "bottom-left",
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          offsetOrigin: "top-right",
          offset: [0, 1], //偏移量设置
          scale: 0.08, //图标缩放比例
        }),
        text: new Text({
          text: '测试名称',
          fill: new Fill({
            color: "#fff",
          }),
          offsetY: -50,
        })
      });
    
      const clusters = new VectorLayer({
        source: new VectorSource({
          features: features,
        }),
        style: iconStyle,
        ...options,
      });
      map.value!.addLayer(clusters);
    }
    
    // 请求数据
    function onLoad() {
      try {
        if (!state.name) return;
        state.loading = true;
        getArea(state.name).then(res => {
          if (res.data.code === 200) {
            if (res.data.data instanceof Array) {
              state.mapData = res.data.data;
              addMarker(state.mapData, { name: "block" });
            }
          }
          state.loading = false;
        });
      } catch (e) {
        state.loading = false;
      }
    }
    
    script>
    
    <style>
    .my_map {
      width: 100%;
      height: 800px;
    }
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
  • 相关阅读:
    代码随想录算法训练营Day60|单调栈01
    国际物流和跨境电商物流的区别
    gstreamer-基础教程8
    基于RNN和Transformer的词级语言建模 代码分析 _generate_square_subsequent_mask
    每日一练:LeeCode-9、回文数【字符串】
    软件测试面试题:缺陷记录应包含的内容?
    js 删除数组中指定元素——5种方式
    python模块hmac,hmac哈希算法库
    大数据ClickHouse进阶(二十七):ClickHouse服务监控
    python学习--文件读写操作
  • 原文地址:https://blog.csdn.net/m0_46690660/article/details/128078456