vue 中 mapbox 的使用 ,(同一页面进行多次切换操作)

一、vue 中 引入 mapbox (同一页面进行多次切换操作)

1.mapbox的 底图用天地图

// 1准备工作
安装 @mapbox/mapbox-gl-geocoder
npm install --save @mapbox/mapbox-gl-geocoder
安装 mapbox-gl
npm install --save mapbox-gl

2.图片展示

vue 中 mapbox 的使用 ,(同一页面进行多次切换操作)_第1张图片

3.代码

<template>
  <div class="map-box-inspect">
     // 1.地图的容器
    <div
      id="inspectMap"
      :style="{ height: height + 'px', width: width + 'px' }"
     >
    </div>
    // 2.地图的经纬度、放大级别
    <div class="calculation-box">
      <div class="bottom">
        <div>级别:{{ currentZoom }}</div>
        <div>经度:{{ lng }}</div>
        <div>纬度:{{ lat }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import "mapbox-gl/dist/mapbox-gl.css";
// 引入语言包(引入天地图后 ,mapbox 原生的 地名就失效了)
import MapboxLanguage from "@mapbox/mapbox-gl-language";
// 搜索控件
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";
// 点击图斑展示 弹框不支持vue语法,重写vue挂载组件的方法
import { createApp, ref, h } from "vue";
import pop from "./pop.vue";
// 引入地图
const mapboxgl = require("mapbox-gl");
export default {
  name: "inspectMap",
  props: {
    height: {
      type: Number,
      default: null,
    },
    width: {
      type: Number,
      default: null,
    },
    mapData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      map: null,
      center: [116.177794023, 39.905043954],
      tbfwData: "", // 图斑范围数据
      arrowData: [], // 箭头的数据
      featuresData: [], // 箭头数据源
      flyCoordinates: [], // 飞过去的中心点
      picCoordinates: [], // 获取当前照片的经纬度
      tbObj: {}, // 图斑对象
      layers: [], // 图层
      lng: "", // 经度
      lat: "", // 维度
      currentZoom: "", //当前 地图的放大级别
      flyZoom: 16, //飞过去的放大级别
    };
  },
  mounted() {
    // this.initMap();
  },
  beforeDestroy() {
    this.map.remove();
  },
  watch: {
    // 地图所需要的数据
    mapData: {
      immediate: false,
      deep: true,
      handler: function (newVal, oldVal) {
        if (newVal !== null) {
          // console.log("@地图需要的数据", newVal);
          // 处理图斑范围
          this.tbfwData = newVal.tbfw;
          this.tbObj = JSON.parse(this.tbfwData);
          this.flyCoordinates = this.tbObj.coordinates[0][0][0];
          // 处理箭头的范围
          let arr1 = [];
          this.arrowData = newVal.arrow;
          this.arrowData.forEach((item, index) => {
            let obj = {
              type: "Feature",
              properties: {
                description: "箭头的信息",
                Name: "拍摄角度1", //图标注释内容
                icon: "arrow-r",
                rotate: 60,
              },
              geometry: {
                type: "Point",
                coordinates: [116.17383, 39.9014],
              },
            };
            obj.properties.rotate = item.psjd;
            obj.geometry.coordinates = [item.longitude, item.latitude];
            obj.properties.fjmc = item.fjmc;
            arr1.push(obj);
            return arr1;
          });
          this.featuresData = arr1;
          // 处理附件名称(点击图片  拍摄角度定位)
          this.featuresData.forEach((item, index) => {
            item.properties.icon = "arrow-r";
            if (item.properties.fjmc === newVal.currentFjmc) {
              // console.log("当前item", item);
              item.properties.icon = "arrow-g";
              // 点击照片下查看获取的经纬度
              this.picCoordinates = item.geometry.coordinates;
              this.flyCoordinates = this.picCoordinates;
            }
          });
          // 异步绘制地图
          if (this.picCoordinates[0] === 0 || this.picCoordinates[1] === 0) {
            this.$message.error(`该照片没有经纬度`);
          } else {
            this.$nextTick(() => {
              // this.flyZoom = 18;
              this.initMap();
            });
          }
        }
      },
    },
  },
  methods: {
    // showTbAndArrow()
    // this.map.remove(); // 移除 整个地图(看需求使用)
    initMap() {
      if (this.map) {
        // 地图切换的时候,之前有地图
        // 先清除箭头 后加载 箭头
        this.clearArrowLayerFn();
        this.loadArrowLayersFn();
        // 先清除图斑 后加载 图斑
        this.clearTbLayerFn();
        this.loadTbLayersFn();
        this.flyTo();
      } else {
        // 地图 切换的时候没有地图 (第一次进入)重新加载
        mapboxgl.accessToken =
          "pk.eyJ1IjoiY2FvcnVpYmluIiwiYSI6ImNsYWR3MjEwMjA5b2UzcW85dmZlbTVtMTAifQ.4v81PyG-oZ6TVL7IuyCbrg";
        // eslint-disable-next-line no-unused-vars
        this.map = new mapboxgl.Map({
          container: "inspectMap",
          style: {
            version: 8,
            sources: {
              "tian-satellite1": {
                type: "raster",
                tiles: [
                  "http://t0.tianditu.gov.cn/img_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles",
                ],
                tileSize: 256,
                minzoom: 0,
                maxzoom: 18,
              },
            },
            layers: [
              {
                id: "tian-satellite1",
                type: "raster",
                source: "tian-satellite1",
                layout: {
                  visibility: "none",
                },
                minzoom: 0,
                maxzoom: 22,
              },
            ],
            // 配置天地图的字体
            glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
          },
          center: [116.177794023, 39.905043954],
          zoom: 10,
          // hash: true,
          // zoom: 7.4, // 放大级别
          // pitch: 60,
          // attributionControl: true,
        });
        // 1.加载 全屏控件 , 位置 是 'top-left'
        this.fullscreenControl = new mapboxgl.FullscreenControl();
        this.map.addControl(this.fullscreenControl, "top-left");
        this.loadArrowImg();
        this.map.on("load", (e) => {
          this.map.setFog({}); // 设置天气
          // 1.加载地图的底图 (指定样式图层中布局属性的值。)
          /**
           * layer 要设置布局属性的图层的ID。 (string)
           *  name 要设置的布局属性的名称。 (string)
           * value 布局的值。必须是适合该属性的类型,如Mapbox样式规范中所定义 。 (any)
           *
           */
          this.map.setLayoutProperty(
            "tian-satellite1",
            "visibility",
            "visible"
          );
          // 鼠标移动 - 获取经纬度
          this.map.on("mousemove", (e) => {
            this.lng = e.lngLat.lng.toFixed(8);
            this.lat = e.lngLat.lat.toFixed(8);
          });
          this.currentZoom = this.flyZoom;
          // 当鼠标滚动时,触发事件,获取当前地图缩放级别
          this.map.on("wheel", (e) => {
            let zoom = this.map.getZoom();
            this.currentZoom = parseInt(zoom);
          });
          // 图斑的点击事件, 弹出气泡展示需要的
          this.map.on("click", "tbLayer", (e) => {
            console.log("@eeeee", e.features[0]);
            // // let coordinates = e.features[0].geometry.coordinates.slice();
            // // let description = e.features[0].properties.description;
            // // vue3 中 creatApp 构造 组件传值
            // let value = "传过去的图斑图层的值  ==== 5";
            // const instance = this.mountDomFn(value);
            // new mapboxgl.Popup()
            //   .setLngLat(this.flyCoordinates)
            //   .setDOMContent(instance.$el)
            //   // .setHTML(instance.$el)
            //   .addTo(this.map);
          });
          // this.clearArrowLayerFn();
          this.loadArrowLayersFn();
          // this.clearTbLayerFn();
          this.loadTbLayersFn();
          this.flyTo();
        });
      }
    },
    flyTo() {
      this.map.flyTo({
        // center: [116.4178, 40.222279390523586],
        center: this.flyCoordinates,
        // center: [116.176843924, 39.902070778],
        zoom: this.flyZoom, // 放大级别
        // speed: 0.2,
        // curve: 1,
      });
    },
    // 加载图斑的方法
    loadTbLayersFn() {
      // 1.加载图斑的数据源
      this.map.addSource("tbSource", {
        type: "geojson",
        data: this.tbObj,
      });
      // 2.加载图斑图层
      this.map.addLayer({
        id: "tbLayer",
        type: "fill",
        source: "tbSource",
        layout: {},
        paint: {
          "fill-color": "#fff",
          "fill-opacity": 0.5,
          "fill-outline-color": "red",
          // "line-color": "red",
          // "line-opacity": 1,
          // "line-width": 2,
        },
      });
      // 3.鼠标进入图层的样式
      this.map.on("mouseenter", "tbLayer", (e) => {
        this.map.getCanvas().style.cursor = "pointer";
      });
      // 4.鼠标移除图层的样式
      this.map.on("mouseleave", "tbLayer", () => {
        this.map.getCanvas().style.cursor = "";
      });
    },
    // 加载箭头图片
    loadArrowImg() {
      // 加载箭头图片
      let url = "./resource/arrow-g.png";
      let url1 = "./resource/arrow-r.png";
      this.map.loadImage(url, (error, image) => {
        // console.log(error);
        this.map.addImage("arrow-g", image);
      });
      this.map.loadImage(url1, (error, image) => {
        // console.log(error);
        this.map.addImage("arrow-r", image);
      });
    },
    // 加载箭头图层
    loadArrowLayersFn() {
      if (this.arrowData.length > 0) {
        // 添加箭头数据源
        this.map.addSource("arrowSource", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            name: "拍摄角度",
            features: this.featuresData,
          },
        });
        // 添加箭头图层
        this.map.addLayer({
          id: "arrowLayer",
          type: "symbol",
          source: "arrowSource",
          layout: {
            "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
            "icon-image": ["get", "icon"],
            "text-field": ["get", "Name"], //此属性对应图标注释,必须拥有
            "icon-ignore-placement": true,
            "text-offset": [0, 1.25], //设置图标与图标注相对之间的距离
            "text-anchor": "top",
            "icon-size": 0.4, //图标的大小
            "icon-rotation-alignment": "map", // 地图旋转时图标的对齐方式(可选,可选值为 map、viewport、auto,默认值为 auto)
            "icon-rotate": ["get", "rotate"], // 图标的顺时针旋转角度(可选,默认值为 0,单位:角度)
            "text-size": 10,
          },
          paint: {
            // "text-halo-color": "red",
            "text-halo-color": "rgb(255,255,255)",
            "text-halo-width": 0.5,
          },
        });
        // 点击箭头
        this.map.on("click", "arrowLayer", (e) => {
          console.log("@eeeee", e.features[0]);
          // let coordinates = e.features[0].geometry.coordinates.slice();
          // let description = e.features[0].properties.description;
          // console.log("@箭头详情", description);
          // // Ensure that if the map is zoomed out such that multiple
          // // copies of the feature are visible, the popup appears
          // // over the copy being pointed to.
          // while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
          //   coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
          // }
          // // vue3 中 creatApp 构造 组件传值
          // let value = "传过去 箭头的值"; // 给子组件传过去的数据
          // const instance = this.mountDomFn(value);
          // new mapboxgl.Popup()
          //   .setLngLat(coordinates)
          //   .setDOMContent(instance.$el)
          //   // .setHTML(instance.$el)
          //   .addTo(this.map);
        });
        // 鼠标移入箭头图层
        this.map.on("mouseenter", "arrowLayer", () => {
          this.map.getCanvas().style.cursor = "pointer";
        });
        // 鼠标移出箭头图层
        this.map.on("mouseleave", "arrowLayer", () => {
          this.map.getCanvas().style.cursor = "";
        });
      }
    },
    // 清除图斑的方法
    clearTbLayerFn() {
      if (this.map && this.map.getLayer("tbLayer")) {
        this.map.removeLayer("tbLayer");
      }
      if (this.map && this.map.getSource("tbSource")) {
        this.map.removeSource("tbSource");
      }
    },
    // 清除箭头的方法
    clearArrowLayerFn() {
      if (this.map && this.map.getLayer("arrowLayer")) {
        this.map.removeLayer("arrowLayer");
      }
      if (this.map && this.map.getSource("arrowSource")) {
        this.map.removeSource("arrowSource");
      }
    },

    // 清除所有图层
    clearLayerFn() {
      // console.log("@获取图层",this.map.getStyle().layers);
      this.clearTbLayerFn();
      this.clearArrowLayerFn();
    },
    // vue 挂载 Dom 的方法
    mountDomFn(value) {
      // vue3 中 creatApp 构造 组件传值
      // let value = "123123";
      /**
       * @params pop   是 导入的 vue 组件
       * @params objes 是 子组件中用于接收 当前页面传给 pop 组件的值
       *
       * */
      let app = createApp(
        h(pop, {
          objes: value || "传过去的值是 6666",
        })
      );
      // console.log("@app111", app);
      // 提供一个父元素
      const parent = document.createElement("div");
      //mount方法不再像vue2一样支持未挂载的实例,必须得挂载,即必须得给参数
      const instance = app.mount(parent);
      // 返回
      return instance;
    },
  },
};
</script>
<style lang="less" scoped>
.map-box-inspect {
  position: relative;
  width: 100%;
  height: 100%;
  //   background-color: pink;
  #inspectMap {
    width: 100%;
    height: 100%;
    /deep/ .mapboxgl-canvas {
      // width: 100%;
      // height: 100%;
    }
    /deep/ .mapboxgl-control-container {
      .mapboxgl-ctrl-bottom-left {
        .mapboxgl-ctrl {
          .mapboxgl-ctrl-logo {
            display: none;
          }
        }
      }
      .mapboxgl-ctrl-bottom-right {
        // .mapboxgl-ctrl mapboxgl-ctrl-attrib
        .mapboxgl-ctrl-attrib-inner {
          display: none;
        }
        .mapboxgl-compact {
          display: none;
        }
      }
    }
  }
  .calculation-box {
    height: 30px;
    width: 100%;
    position: absolute;
    bottom: 0px;
    left: 0px;
    background-color: rgba(255, 255, 255, 0.8);
    // border: 1px solid red;
    // padding: 15px;
    text-align: center;
    .bottom {
      line-height: 30px;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>

4.模拟地图所需的数据

vue 中 mapbox 的使用 ,(同一页面进行多次切换操作)_第2张图片

{
    "tbfw": "{\"type\":\"MultiPolygon\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4490\"}},\"coordinates\":[[[[116.179832229,39.904137042],[116.180285516,39.904165596],[116.180306946,39.903825399],[116.179853659,39.903796847],[116.179832229,39.904137042]]]]}",
    "arrow": [
        {
            "latitude": 39.904186,
            "longitude": 116.17795,
            "psjd": 198,
            "fjmc": "Pictures1675057477621.jpg"
        }
    ],
    "currentFjmc": ""
}

你可能感兴趣的:(mapbox,vue.js,javascript,前端)