临时AMAP

阅读 51

2022-01-20


```javascript
<template>
  <div id="map-container">
    <div v-if="isPatrol" class="menu br">
      <button @click="draw">绘制</button>
      <button @click="edit">编辑</button>
      <button @click="polyEditor.close()">结束</button>
    </div>
    <div class="menu tr">
      <button v-if="isPatrol" @click="drawRule">
        {{ ruleState ? "关闭测距" : "开启测距" }}
      </button>
      <button @click="changeTheme('darkblue')">深色主题</button>
      <button @click="changeTheme('normal')">浅色主题</button>
      <button @click="toggleFullScreen">
        {{ startInitPatrolSet ? "关闭全屏并结束" : "全屏" }}
      </button>
    </div>
    <div v-if="isPatrol" class="map-control">
      <i
        v-if="!isPlay"
        class="el-icon-video-play"
        style="font-size: 24px; vertical-align: middle"
        @click="
          isPlay = true;
          navgControl('start');
        "
      />
      <i
        v-else
        class="el-icon-video-pause"
        style="font-size: 24px; vertical-align: middle"
        @click="
          isPlay = false;
          navgControl('pause');
        "
      />
      <!-- <span class="passed-time">{{ passedTime }}</span> -->
      <!-- <el-slider
        class="map-slider"
        v-model="sliderVal"
        :show-tooltip="false"
        :step="0.0001"
      ></el-slider> -->
      <div
        class="map-times"
        @mouseenter="isTimesChoose = true"
        @mouseleave="isTimesChoose = false"
      >
        <div class="times-show">倍速 {{ times }}</div>
        <div class="choose-box">
          <ul v-show="isTimesChoose">
            <li
              v-for="item in speedList"
              :key="item"
              :class="{ active: times === item }"
              @click="changeSpeed(item)"
            >
              倍速 {{ item }}
            </li>
          </ul>
        </div>
      </div>
      <span class="passed-time">{{ totalTime }}</span>
    </div>
    <div style="display: none">
      <HeatSource ref="heatSource" :data="dialogData" />
      <Compensator ref="compensator" :data="dialogData" />
      <Cleaner ref="cleaner" :data="dialogData" />
      <Valve ref="valve" :data="dialogData" />
      <PipeLine ref="pipeLine" :data="dialogData" />
      <Exchange ref="exchange" :data="dialogData" />
      <Monitor ref="monitor" :data="dialogData" />
      <Well ref="well" :data="dialogData" />
    </div>
  </div>
</template>

<script>
/**
 * Import Amap-Vue based on Gaode-map on demand
 * https://jimliu.net/amap-vue/
 */
import AMapLoader from "@amap/amap-jsapi-loader";
import { mapGetters } from "vuex";
import HeatSource from "./MapDialog/HeatSource";
import Compensator from "./MapDialog/Compensator";
import Cleaner from "./MapDialog/Cleaner";
import Valve from "./MapDialog/Valve";
import PipeLine from "./MapDialog/PipeLine";
import Exchange from "./MapDialog/Exchange";
import Monitor from "./MapDialog/Monitor";
import Well from "./MapDialog/Well";
import { cloneDeep } from "lodash";
import http from "@/apis/geoInfo";
import { server_config } from "/public/config";
export default {
  name: "AMap",
  props: ["listener"],
  components: {
    HeatSource,
    Compensator,
    Cleaner,
    Valve,
    PipeLine,
    Exchange,
    Monitor,
    Well,
  },
  data() {
    return {
      layer: {},
      dialogData: {
        notes: "站位",
      },
      timesChanged: false,
      map: null, // 地图
      poly: null, // 多边形
      polyEditor: null, // 多边形编辑器
      ruleState: false, // 测距状态
      ruler: null, //测距工具
      heatSource: [], // 热源多边形数组
      exchange: [], //换热站
      heatArea: [], //供热区域
      monitor: [], // 计量站
      wellCap: [], //井盖
      steamValve: [], //排气阀
      bridge: [], //勾手
      cleaner: [], // 除污器
      compensator: [], //补偿器
      valve: [], //阀门
      pipeLine: [], // 管网
      fiber: [], // 光纤
      isOnSlider: false, //是否为手动鼠标拉动进度条
      playIcon: "resume", //开始按钮是重新开始还是继续
      isTimesChoose: false, //选择速度弹窗的open/close
      passedTime: "00:00:00", //已经走了的时间
      totalTime: "00:00:00", //一共走了的时间
      isPlay: false, //是否为播放
      sliderVal: 0, //进度条滑动速度
      speed: 100, //初始速度,km/h
      times: 1, //几倍速度播放
      navgtr: null, //巡航器
      speedList: [8, 4, 2, 1],
      pathList: [],
      trackList: [],
      lat: "",
      lng: "",
      moveConfig: [],
      moveIdx: 0,
      markers: [],
      passedPolylines: [],
      polylines: [],
      startInitPatrolSet: false,
      closeFullScreen: false,
      isFirstLoad: true,
      imageLayer: null,
      config:
        process.env.NODE_ENV === "production"
          ? server_config.production
          : process.env.NODE_ENV === "debug"
          ? server_config.debug
          : server_config.development,
      configSubPipeline: {},
    };
  },
  computed: {
    ...mapGetters({
      token: "getToken",
    }),
    mode() {
      return this.$store.state.mode;
    },
    isPatrol() {
      return this.$route.path === "/Map/Patrol";
    },
  },
  beforeCreate() {
    // 加载地图
    AMapLoader.load({
      key: "1ccc7c0c495f09e0a1f663b5fb21bb7c", // 申请好的Web端开发者Key,首次调用 load 时必填
      version: "1.4.15", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
      plugins: [
        "AMap.MouseTool",
        "AMap.ElasticMarker",
        "AMap.Scale",
        "AMap.PolyEditor",
        "AMap.RangingTool",
        "AMap.DistrictSearch",
        "AMap.Polygon",
        "AMap.Polyline",
        "AMap.Marker",
        "AMap.MoveAnimation",
      ], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      AMapUI: {
        // 是否加载 AMapUI,缺省不加载
        version: "1.1", // AMapUI 缺省 1.1
      },
    })
      .then((AMap) => {
        this.initMap(AMap);
        window.AMap = AMap;
        this.initWeather(AMap);
      })
      .catch((e) => {
        console.error(e);
      });
    document.addEventListener("fullscreenchange", () => {
      if (this.startInitPatrolSet) {
        if (this.closeFullScreen) {
          this.toggleFullScreen();
          this.closeFullScreen = false;
        } else {
          this.closeFullScreen = true;
        }
      }
    });
  },
  mounted() {
    this.addElement();
    this.updateElement();
    this.deleteElement();
    this.initPatrolSet();
    this.$EventBus.$on("clear-map", () => {
      this.clearMap();
    });
    this.$EventBus.$on("updateSubPipeline", ({ type, checked, systemId }) => {
      this.configSubPipeline[type] = { checked, systemId };
      console.log(type, checked, systemId);
      this.addSubPipeline();
    });
  },
  methods: {
    getBounds() {
      const bounds = this.map.getBounds();
      let width = Math.abs(bounds.northeast.lng - bounds.southwest.lng);
      let height = Math.abs(bounds.northeast.lat - bounds.southwest.lat);
      const longitude = bounds.southwest.lng;
      const latitude = bounds.northeast.lat;
      if (this.isFirstLoad) {
        this.isFirstLoad = false;
        http
          .getGeoList({
            width,
            height,
            longitude,
            latitude,
          })
          .then((res) => {
            this.$store.commit("setLayerData", res);
            this.$EventBus.$emit("getLayerEnd");
          });
      }
      //添加图层
      this.addSubPipeline();
    },
    addSubPipeline(systemId) {
      //删除图层
      if (this.layer.imageLayer) {
        this.map.remove(this.layer.imageLayer);
        this.layer.imageLayer.splice(0);
      } else {
        this.layer.imageLayer = [];
      }
      Object.keys(this.configSubPipeline).forEach((key) => {
        const { checked, systemId } = this.configSubPipeline[key];
        if (checked) {
          const mapSize = this.map.getSize();
          const width = mapSize.width;
          const height = mapSize.height;
          const northEastLng = this.map.getBounds().northeast.lng;
          const northEastLat = this.map.getBounds().northeast.lat;
          const southWestLng = this.map.getBounds().southwest.lng;
          const southWestLat = this.map.getBounds().southwest.lat;
          const imageLayer = new AMap.ImageLayer({
            bounds: this.map.getBounds(),
            url:
              this.config.baseURL +
              "geoInfo/img?zoom=" +
              this.map.getZoom() +
              "&width=" +
              width +
              "&height=" +
              height +
              "&northEastLng=" +
              northEastLng +
              "&northEastLat=" +
              northEastLat +
              "&southWestLng=" +
              southWestLng +
              "&southWestLat=" +
              southWestLat +
              "&systemId=" +
              systemId, // 图片 Url
            zIndex: 2,
            zooms: [3, 18], // 设置可见级别,[最小级别,最大级别]
          });
          this.layer.imageLayer.push(imageLayer);
          this.map.add(this.layer.imageLayer);
        }
      });
    },
    // 初始化地图
    initMap(AMap) {
      this.map = new AMap.Map("map-container", {
        zoom: 14,
        resizeEnable: true,
        mapStyle: "amap://styles/darkblue",
      });
      this.map.on("click", function(e) {
        console.log(e.lnglat.getLng() + "," + e.lnglat.getLat());
      });
      this.map.on("moveend", this.getBounds);
      //  this.map.on("zoomend", this.getBounds);
      // this.map.on("mousewheel", () => {
      //   console.log(this.map.getResolution());
      // });
      // this.map.setCity('天津市')
      this.districtModal(AMap); // 若不需要此功能,注释掉代码就好
    },
    // 显示目标城市目标行政区域,外部遮罩。可根据业务需求修改城市adcode。若不需要此功能,可不调用此方法。
    districtModal(AMap) {
      let _this = this;
      new AMap.DistrictSearch({
        extensions: "all", // 是否返回行政区边界坐标点
        subdistrict: 0,
      }).search("120116", (status, result) => {
        //"120116"为天津市滨海新区adcode,此参数也可以写‘滨海新区’
        const { lat, lng } = result.districtList[0].center;
        this.lat = lat;
        this.lng = lng;
        let outer = [
          new AMap.LngLat(-360, 90, true),
          new AMap.LngLat(-360, -90, true),
          new AMap.LngLat(360, -90, true),
          new AMap.LngLat(360, 90, true),
        ];
        let holes = result.districtList[0].boundaries; // 行政区域边界
        let arr = [];
        holes.forEach((item) => {
          arr.push(item.length);
        });
        let indexMax = 0;
        arr.forEach((item, index) => {
          if (item === Math.max(...arr)) {
            indexMax = index;
          }
        });
        let pathArray = [outer];
        pathArray.push.apply(pathArray, [holes[indexMax]]);
        // innerPolygon 为行政区域边界多边形
        let innerPolygon = new AMap.Polygon({
          path: pathArray,
          // 线条颜色,使用16进制颜色代码赋值。默认值为#006600
          strokeColor: "#1892FC",
          strokeWeight: 1,
          // 多边形填充颜色,使用16进制颜色代码赋值,如:#FFAA00
          fillColor: "#0f1c2d",
          // 多边形填充透明度,取值范围[0,1],0表示完全透明,1表示不透明。默认为0.9
          fillOpacity: 0.8,
        });
        // outerPolygon 只为setFitView, 未在地图展示
        let outerPolygon = new AMap.Polygon({
          path: holes[indexMax],
        });
        innerPolygon.setPath(pathArray);
        _this.map.add(innerPolygon);
        _this.map.setFitView(outerPolygon);
        // _this.map.setZoom(_this.getZoom() + 0.5) // 设置放大倍数
      });
    },
    // 添加标记
    addMarker() {
      let marker = new AMap.Marker({
        icon:
          "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [104.065695, 30.657522],
        offset: new window.AMap.Pixel(-13, -30),
      });
      marker.setMap(this.map);
    },
    // 绘制多边形
    draw() {
      let vm = this;
      let mouseTool = new AMap.MouseTool(this.map);
      mouseTool.polygon({
        strokeColor: "#FF33FF",
        strokeOpacity: 1,
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillColor: "#1791fc",
        fillOpacity: 0.4,
        // 线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        // strokeDasharray: [30,10],
      });
      mouseTool.on("draw", function(event) {
        // event.obj 为绘制出来的覆盖物对象
        vm.poly = event.obj;
        console.log(event);
        mouseTool.close();
      });
    },
    // 编辑多边形
    edit() {
      var polyEditor = new AMap.PolyEditor(this.map, this.poly);
      this.polyEditor = polyEditor;
      polyEditor.on("addnode", function(event) {
        console.log("触发事件:addnode");
      });

      polyEditor.on("adjust", function(event) {
        console.log("触发事件:adjust");
      });

      polyEditor.on("removenode", function(event) {
        console.log("触发事件:removenode");
      });

      polyEditor.on("end", function(event) {
        console.log("触发事件: end");
        // event.target 即为编辑后的多边形对象
        console.log(event.target.getPath());
      });
      polyEditor.open();
    },
    // 换主题
    changeTheme(name) {
      const styleName = `amap://styles/${name}`;
      this.map.setMapStyle(styleName);
    },
    // 切换全屏
    toggleFullScreen() {
      if (this.startInitPatrolSet) {
        Object.keys(this.layer).forEach((key) => {
          if (
            ["userOnline", "markers", "passedPolylines", "polyline"].includes(
              key
            )
          ) {
            this.layer[key] && this.map.remove(this.layer[key]);
          }
        });
        this.startInitPatrolSet = false;
        this.isPlay = false;
        if (document.exitFullscreen) {
          this.map.setZoom(this.map.getZoom() - 0.5);
          this.closeFullScreen = false;
          document.exitFullscreen();
        }
      } else {
        this.startInitPatrolSet = true;

        if (!document.fullscreenElement) {
          const map = document.querySelector("#map-container");
          map.requestFullscreen();
          this.map.setZoom(this.map.getZoom() + 0.5);
        }
      }
    },
    // 测距
    drawRule() {
      if (!this.ruleState) {
        const ruler = new AMap.RangingTool(this.map, {
          startMarkerOptions: {
            //可缺省
            icon: new AMap.Icon({
              size: new AMap.Size(19, 31), //图标大小
              imageSize: new AMap.Size(19, 31),
              image: "https://webapi.amap.com/theme/v1.3/markers/b/start.png",
            }),
          },
          endMarkerOptions: {
            //可缺省
            icon: new AMap.Icon({
              size: new AMap.Size(19, 31), //图标大小
              imageSize: new AMap.Size(19, 31),
              image: "https://webapi.amap.com/theme/v1.3/markers/b/end.png",
            }),
            offset: new AMap.Pixel(-9, -31),
          },
          midMarkerOptions: {
            //可缺省
            icon: new AMap.Icon({
              size: new AMap.Size(19, 31), //图标大小
              imageSize: new AMap.Size(19, 31),
              image: "https://webapi.amap.com/theme/v1.3/markers/b/mid.png",
            }),
            offset: new AMap.Pixel(-9, -31),
          },
          lineOptions: {
            //可缺省
            strokeStyle: "solid",
            strokeColor: "#FF33FF",
            strokeOpacity: 1,
            strokeWeight: 2,
          },
          //同 RangingTool 的 自定义 设置,缺省为默认样式
        });
        this.ruler = ruler;
        this.ruleState = true;
        ruler.turnOn();
      } else {
        this.ruleState = false;
        this.ruler.turnOff();
      }
    },
    updateElement() {
      this.$EventBus.$on(
        "updateElement",
        ({ mapType, dataName, updateConfigs }) => {
          updateConfigs.forEach(({ id, config }) => {
            if (mapType === "Polyline") {
              const data = this.layer[dataName].find((el) => el.id === id);
              data.setOptions(config);
            }
          });
        }
      );
    },
    // 在地图上添加
    addElement() {
      this.$EventBus.$on("addElement", (obj) => {
        const cloneDeepObj = cloneDeep(obj);
        const { mapType, dataName, config = {} } = obj;
        if (obj.mapType) {
          for (let i = 0; i < obj.elementLocaton.length; i++) {
            let data = null;
            if (mapType === "Polygon") {
              data = new AMap.Polygon({
                path: obj.elementLocaton[i],
                // 线条颜色,使用16进制颜色代码赋值。默认值为#006600
                strokeColor: obj.elementPathColor,
                // 轮廓线宽度
                strokeWeight: 1,
                // 多边形填充颜色,使用16进制颜色代码赋值,如:#FFAA00,根据设备或区域自行设置
                fillColor: obj.elementPathColor,
                // 多边形填充透明度,取值范围[0,1],0表示完全透明,1表示不透明。默认为0.9
                fillOpacity: 0.5,
                // 轮廓线透明度,取值范围 [0,1] ,0表示完全透明,1表示不透明。默认为0.9
                strokeOpacity: 0.5,
                ...config,
              });
            } else if (mapType === "Polyline") {
              data = new window.AMap.Polyline({
                path: obj.elementLocaton[i],
                // 线条颜色,使用16进制颜色代码赋值。默认值为#006600
                strokeColor: obj.elementPathColor,
                // 轮廓线宽度
                strokeWeight: 1,
                // 多边形填充颜色,使用16进制颜色代码赋值,如:#FFAA00,根据设备或区域自行设置
                fillColor: obj.elementPathColor,
                // 多边形填充透明度,取值范围[0,1],0表示完全透明,1表示不透明。默认为0.9
                fillOpacity: 0.5,
                // 轮廓线透明度,取值范围 [0,1] ,0表示完全透明,1表示不透明。默认为0.9
                strokeOpacity: 0.5,
                ...config,
              });
              data.id = obj.id;
              data.on("click", () => {
                obj.onClick && obj.onClick();
              });
            } else if (mapType === "Marker") {
              // console.log('map obj.elementLocaton', obj.elementLocaton[i])
              data = new AMap.Marker({
                // 点标记位置
                position: obj.elementLocaton[i],
                // 点标记图片
                icon: new AMap.Icon({
                  // 图标尺寸
                  imageOffset: new AMap.Pixel(6, 16),
                  // 图标的取图地址,可用本地图片,可用网络图片
                  image: obj.image,
                  // 图标所用图片大小
                  imageSize: new AMap.Size(20, 20),
                }),
                ...config,
              });
            } else if (mapType === "Text") {
              data = new AMap.Text({
                // 点标记位置
                offset: new AMap.Pixel(0, 0),
                position:
                  typeof cloneDeepObj.elementLocaton[0][0] === "number"
                    ? cloneDeepObj.elementLocaton[0]
                    : cloneDeepObj.elementLocaton[0][0],
                zIndex: 16,
                ...config,
              });
            }

            if (this.$refs[obj.refName]) {
              AMap.event.addListener(data, "click", async () => {
                console.log("--> data", data);
                if (obj.onClick) {
                  this.infoWindow = new AMap.InfoWindow({
                    content: this.$refs[obj.refName].$el,
                    isCustome: true,
                    offset: new AMap.Pixel(-4, -36),
                  });
                  const res = await obj.onClick(obj.id);
                  this.dialogData = res;
                  this.infoWindow.open(
                    this.map,
                    mapType === "Marker"
                      ? data.getPosition()
                      : obj.elementLocaton[0][0]
                  );
                }
              });
            }

            if (!this.layer[dataName]) {
              this.layer[dataName] = [];
            }
            if (data) {
              this.layer[dataName].push(data);
              this.layer[dataName] && this.map.add(this.layer[dataName]);
            }
            // 添加点
          }
        }
      });
    },
    // 从地图上删除
    deleteElement() {
      this.$EventBus.$on("deleteElement", (dataName) => {
        this.infoWindow && this.infoWindow.close(this.map);
        if (this.layer[dataName] && this.layer[dataName].length) {
          this.map.remove(this.layer[dataName]);
          this.layer[dataName].splice(0);
        }
      });
    },
    initPatrolSet() {
      this.$EventBus.$on("initPatrolSet", async ({ paths, users }) => {
        this.toggleFullScreen();
        // this.allFullScreen
        this.initPathCallback = () => {
          return new Promise((resolve, reject) => {
            this.moveIdx = 0;
            if (!this.layer.markers) {
              this.layer.markers = [];
            }
            if (!this.layer.passedPolylines) {
              this.layer.passedPolylines = [];
            }
            if (!this.layer.polyline) {
              this.layer.polyline = [];
            }
            this.map.remove(this.layer.markers);
            this.map.remove(this.layer.passedPolylines);
            this.map.remove(this.layer.polyline);

            this.layer.markers.splice(0);
            this.layer.passedPolylines.splice(0);
            this.layer.polyline.splice(0);
            this.isPlay = false;
            this.resumeMove();
            this.$nextTick(() => {
              this.initMapPath(paths, users);
              resolve();
            });
          });
        };
        await this.initPathCallback();
      });
    },
    initMapPath(paths, users) {
      paths.forEach(({ id, path, timestamps }) => {
        const initPath = cloneDeep(path);
        const marker = new AMap.Marker({
          map: this.map,
          position: path[0],
          offset: new AMap.Pixel(-10, -13),
          icon: new AMap.Icon({
            size: new AMap.Size(25, 25), //图标大小
            imageSize: new AMap.Size(25, 25),
            image: require("@/assets/img/map-icons/user-online.png"),
          }),
          autoRotation: false,
          label: {
            content: users.find((item) => item.id === id).name,
            direction: "top",
          },
        });
        // 绘制轨迹
        const polyline = new AMap.Polyline({
          map: this.map,
          path,
          showDir: true,
          strokeColor: "#28F", //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 10, //线宽
          // strokeStyle: "solid"  //线样式
        });
        marker.on("moveend", (e) => {});
        marker.on("moving", (e) => {
          // 脏数据太多了
          passedPolyline.setPath(e.passedPath);
        });
        const passedPolyline = new AMap.Polyline({
          map: this.map,
          // path: lineArr,
          strokeColor: "#AF5", //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6, //线宽
          // strokeStyle: "solid"  //线样式
        });
        this.moveConfig.push({
          // 开始动画
          start: () => {
            marker.moveAlong(path, 100 * this.times);
          },
          // 继续动画
          resume: () => {
            marker.resumeMove();
          },
          // 暂停动画
          pause: () => {
            marker.pauseMove();
          },
        });
        this.layer.polyline.push(polyline);
        this.layer.passedPolylines.push(passedPolyline);
        this.layer.markers.push(marker);
        if (!this.layer.markers) {
        }
      });
    },
    startMove() {
      this.moveConfig.forEach(({ start }) => {
        start();
      });
    },
    resumeMove() {
      this.moveConfig.forEach(({ resume }) => {
        resume();
      });
    },
    stopMove() {
      this.moveConfig.forEach(({ pause }) => {
        pause();
      });
    },
    // 开始、暂停、继续等操作
    navgControl(action) {
      if (action === "start") {
        if (this.timesChanged) {
          this.startMove();
          this.startMove.end = true;
          this.timesChanged = false;
        }
        if (!this.startMove.end) {
          this.startMove();
          this.startMove.end = true;
        } else {
          this.timesChanged = false;
          this.resumeMove();
        }
      } else {
        this.stopMove();
      }
    },
    openSlider() {
      this.isOnSlider = true;
    },
    closeSlider() {
      this.isOnSlider = false;
    },
    // 修改倍速
    changeSpeed(times) {
      this.isTimesChoose = false;
      this.times = times;
      this.timesChanged = true;
      this.startMove.end = false;
      this.isPlay = false;
      this.stopMove();
    },
    sliderChange(val) {
      let newVal = typeof newVal === "number" ? val : this.sliderVal;
      let num = parseInt((newVal / 1000) * this.pathList.length);
      let decimal =
        String((newVal / 100) * this.pathList.length).split(".")[1] || 0;
      this.navgtr.moveToPoint(num, Number("0." + decimal));
      this.pathSimplifierIns.renderLater();
    },
    clearMap() {
      Object.keys(this.layer).forEach((key) => {
        this.map.remove(this.layer[key]);
        Array.isArray(this.layer[key]) && this.layer[key].splice(0);
      });
      this.infoWindow && this.infoWindow.close(this.map);
    },
    /**
     * use GaoDe api to get current city mail code
     * @param AMap  the GaoDe api AMap class
     * @returns {Promise<result.adcode>} the mail code of the current city
     */
    getCity(AMap) {
      return new Promise(function(resolve, reject) {
        AMap.plugin("AMap.CitySearch", function() {
          const citySearch = new AMap.CitySearch();
          citySearch.getLocalCity(function(status, result) {
            if (status === "complete" && result.info === "OK") {
              // 查询成功,result即为当前所在城市信息
              resolve(result.adcode);
            } else {
              reject(status);
            }
          });
        });
      });
    },
    /**
     * get the current weather information
     * @param AMap the GaoDe api AMap class
     * @param mailCode the mail code location to search the weather
     * @returns {Promise<data>} the weather data of the given mail code location
     */
    getWeather(AMap, mailCode) {
      return new Promise(function(resolve, reject) {
        //加载天气查询插件
        AMap.plugin("AMap.Weather", function() {
          //创建天气查询实例
          const weather = new AMap.Weather();
          //执行实时天气信息查询
          weather.getForecast(mailCode, function(err, data) {
            if (!err) {
              resolve(data);
            } else {
              console.log(err);
              reject(err);
            }
          });
        });
      });
    },
    async initWeather(AMap) {
      //get city main code for get weather
      const cityMailCode = await this.getCity(AMap);
      //get weather data base on the mail code
      const weatherData = await this.getWeather(AMap, cityMailCode);
      this.$store.commit("setWeatherData", weatherData);
    },
  },
  watch: {
    sliderVal(newVal) {
      if (!this.isOnSlider) {
        return false;
      }
      this.sliderChange(newVal);
    },
    mode() {
      this.clearMap();
    },

    $route() {
      this.clearMap();
      this.configSubPipeline = {};
    },
  },

  beforeDestroy() {
    this.$EventBus.$off("addElement");
    this.$EventBus.$off("updateElement");
    this.$EventBus.$off("deleteElement");
    this.$EventBus.$off("initPatrolSet");
    this.$EventBus.$off("clear-map");
    this.map && this.map.destroy();
    this.navgtr = null;
  },
};
</script>

<style scoped>
#map-container {
  position: relative;
  color: #2c3e50;
  width: 100%;
  height: 100%;
}
.menu {
  position: absolute;
  z-index: 5;
}
.menu button {
  -webkit-appearance: none;
  outline: none;
  border: none;
  font-size: 12px;
  cursor: pointer;
  line-height: 1;
  padding: 6px 10px;
  /* border-radius: 3px; */
  margin-left: 6px;
  -webkit-appearance: none;
  background: linear-gradient(0deg, #07368f, #002a78, #07368f);
  border: 1px solid rgba(45, 122, 238, 0.45);
  color: #1ed2ff;
  box-shadow: 0 0 2px 1px #1d55c5 inset;
}
.br {
  right: 0;
  bottom: 0;
}
.tr {
  right: 0;
  top: 0;
}
.el-slider__button-wrapper {
  transition: all 0.2s linear;
  top: -5px;
}
.el-slider__runway {
  background-color: rgba(255, 255, 255, 0.5);
}
.color-tag li {
  display: inline-block;
  border-radius: 4px;
  width: 100px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  background-color: #fff;
  cursor: pointer;
  margin-right: 2px;
}
.color-tag li.color-org {
  background-color: #ff8533;
  color: #fff;
}
.color-tag li.color-green {
  background-color: #46c51a;
  color: #fff;
}
.map-control {
  position: absolute;
  bottom: 0;
  width: 65%;
  left: 0;
  z-index: 200;
  height: 50px;
  line-height: 50px;
  border-radius: 2px;
  color: #1ed2ff;
  background-image: linear-gradient(to top, rgba(1, 63, 116, 0.7), transparent);
  padding: 0 10px;
}
.map-slider {
  display: inline-block;
  width: 45%;
  margin-left: 15px;
  position: relative;
  top: 14px;
}
.passed-time {
  position: relative;
  top: 2px;
  /*display: inline-block;*/
  margin-left: 15px;
  font-size: 12px;
}
.map-times {
  display: inline-block;
  margin-left: 15px;
}
.map-times .times-show {
  padding: 0 4px;
  line-height: 18px;
  font-size: 12px;
  border: 1px solid #1ed2ff;
  border-radius: 4px;
  cursor: pointer;
}
.map-times .choose-box {
  position: absolute;
  top: -60px;
  height: 162px;
  transition: all 0.5s linear;
}
.map-times ul {
  background: rgba(0, 0, 0, 0.7);
  padding: 4px 0;
  width: 70px;
  text-align: center;
  border-radius: 3px;
}
.map-times li {
  height: 18px;
  line-height: 18px;
  cursor: pointer;
  font-size: 12px;
}
.map-times li.active {
  color: #1c99fd;
}
.map-times li:hover {
  font-size: 14px;
}
/*>>> .amap-info-content {*/
/*  padding: 0 18px 0 10px;*/
/*}*/
>>> .el-slider__runway {
  background-color: #909090;
}
>>> .el-slider__button {
  width: 10px;
  height: 10px;
  border: 2px solid #07368f;
  background-color: #1c99fd;
}
</style>


精彩评论(0)

0 0 举报