fenceMap.vue 17.4 KB
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
<template>
  <!-- 围栏调用地图弹框 -->
  <!-- <el-dialog id="fenceMapModal1"  :visible="fenceMapModalVisible" @open="openDialog" @close="closeDialog" append-to-body width="1200px" top="10vh"> -->
  <!-- <div class="dialog-header" slot="title">
			<h2 class="header-title">地图引用</h2>
		        </div> -->

  <div class="fence-map" :visible="fenceMapModalVisible" v-loading="mapLoading">
    <!-- <el-form :model="form" ref="fenceMapForm" :rules="rules" :inline="true" size="mini" >
	        			       <el-form-item label="经度" prop="lng">
	        			       						<el-input v-model="form.lng" style="width:100px" @change="transfer"></el-input>
	        			       			    	</el-form-item>
	        			       			    	<el-form-item label="纬度" prop="lat">
	        			       						<el-input v-model="form.lat" style="width:100px" @change="transfer"></el-input>
	        			       			    	</el-form-item>
	        			       			    	<el-form-item label="经纬度解析" prop="transferAddr">
	        			       						<el-input v-model="form.transferAddr" disabled placeholder="自动生成" style="width: 410px;"></el-input>
	        			       			    	</el-form-item>
	        			       			    	<el-form-item label="监控范围" prop="radius">
	        			       						<el-input v-model="form.radius" style="width:160px" maxlength="10">
	        			       							<template slot="append">KM</template>
	        			       						</el-input>
	        			       			    	</el-form-item>
	        			       			    	<el-form-item><el-button type="primary" @click="updateFence">更新围栏</el-button></el-form-item>
	        			       			    </el-form>-->

    <div id="mapContainer" class="map-container"></div>

    <fence-map-controll
      @onRefreshMap="refreshMap"
      :isModalMap="true"
    ></fence-map-controll>

    <div class="map-seacrh-wrap">
      <!-- <input type="text" id="fenceMapSearch"> -->
      <el-input
        placeholder="请输入搜索地址"
        id="fenceMapSearch"
        size="small"
        maxlength="200"
        v-model="fenceMapSearch"
        :disabled="readonlyStatus"
      >
        <template slot="prepend">搜索</template>
        <!-- <el-button slot="append" icon="el-icon-search" @click="search"></el-button> -->
      </el-input>
    </div>
  </div>
  <!-- <div slot="footer" class="dialog-footer">
		  		
		  		<el-button type="primary" @click="sure" size="small">确认</el-button>
		  		<el-button @click="$emit('onFenceMapModalChange', false)" size="small">关闭</el-button>
		  	</div> -->
  <!-- </el-dialog> -->

  <!-- 围栏调用地图弹框 /-->
</template>
<script>
import remoteLoad from "utils/remoteLoad.js";
// import mapService from "utils/mapService.js";
import mapService from "@/utils/mapBService.js";
import FenceMapControll from "./FenceMapControll.vue";
import { CONSTANT } from "../../constant";
export default {
  props: ["fenceMapModalVisible", "init", "readonlyStatus"],
  data() {
    return {
      fenceMapSearch: "",
      geolocation: null,
      circleEditor: null,
      areaCodeMap: "",
      polygons: [],
      polygonEditor: null,
      autoCenterMarker: null,
      marke: null,
      fenceMapModalVisible: false,
      polygon: null,
      mapDot: true,
      circle: null,
      tableData: [],

      transferTimeoutId: undefined,
      geocoder: null,
      transferFlag: null,
      opts: {
        subdistrict: 1, //返回下一级行政区
        showbiz: false, //最后一级返回街道信息
      },

      mapObj: null,
      fenceType: "polygon", //'area' 'polygon'
      lng: "",
      lat: "",
      radius: 1000,
      fenceCircle: null,
      fenceCenter: null,
      areaCode: "",
      isFenceInit: false,
      mapLoading: false,
      polygonPath: [],
      txtMenuItem: [
        {
          text: "设置围栏中心",
          callback: function () {
            map.zoomIn();
          },
        },
      ],
    };
  },
  mounted() {
    // let _this = this;
    // let plugins = ["AMap.LngLat", "AMap.AutoComplete",'AMap.MouseTool','AMap.PolyEditor'];
    // _this.$mapInit({ version: "1.4.2", plugins: plugins }).then((AMap) => {
    //   window.AMap = AMap;
    //   _this.mapObj = mapService.init("mapContainer");
    //   _this.bindContextMenu();
    //   _this.bindSearch();
    // });
    // this.initBMap();
  },
  watch: {
    lng(newVal) {
      //this.transfer()
    },
    lat(newVal) {
      //this.transfer()
    },
  },
  async created() {
    // this.initBMap();
  },
  methods: {
    async initBMap() {
      this.mapObj = await mapService.init("mapContainer");
      window.AMap = this.mapObj;
      AMap.invoke("LocalCity", (res) => {
        // AMap.invoke('panTo',res.center)
      });
      this.bindContextMenu();
      this.bindSearch();
    },
    initMap() {
      this.initMapPromise = new Promise((resolve, reject) => {
        let check = () => {
          this.checkMapLoaded && window.clearTimeout(this.checkMapLoaded);

          return setTimeout(() => {
            if (
              "AMap" in window &&
              typeof AMap.Map == "function" &&
              !this.mapObj
            ) {
              window.AMap = AMap;
              this.mapObj = mapService.init("mapContainer");

              this.bindContextMenu();
              this.bindSearch();
              resolve();
            } else {
              this.checkMapLoaded = check();
            }
          }, 100);
        };
        this.checkMapLoaded = check();
      });
    },
    bindSearch() {
      let self = this,
        url = require("images/auto-center-marker.gif"),
        size = AMap.invoke("Size", 24, 24);
      self.auto = AMap.invoke("Autocomplete", {
        input: "fenceMapSearch",
      });
      AMap.invoke("autocompleteShow");
      AMap.invoke("autocompleteAddEventListener", "onconfirm", (e) => {
        let location = e.item.value.location;
        AMap.invoke("panTo", location, true);
        self.autoCenterMarker = AMap.invoke("Marker", location, {
          icon: AMap.invoke("Icon", url, size),
        });
        AMap.invoke("markerAddEventListener", "rightclick", (e) => {
          // AMap.invoke("mapAddEventListener", "rightclick", function (e) {
          //   console.log(e,'地图事件')
          // })
          // self.autoCenterMarker.setContextMenu(self.contextMenu)
          self.contextMenuPositon = e.latLng; //右键菜单位置
        });
        self.lng = location.lng;
        self.lat = location.lat;
        AMap.invoke("addOverlay", self.autoCenterMarker);
        AMap.invoke('centerAndZoom', location, 15)
      });
    },
    bindContextMenu() {
      const self = this;
      const MAP = mapService.map;
      var contextMenu = MAP.invoke("ContextMenu");
      contextMenu.addItem(
        MAP.invoke("MenuItem", "设置围栏中心", function () {
          self.moveCenter();
        })
      );
      MAP.invoke("mapAddEventListener", "rightclick", function (e) {
        MAP.invoke("addContextMenu", contextMenu);
        self.contextMenuPositon = e.latlng;
      });
      self.contextMenu = contextMenu;
    },
    drawFence() {
      if (!this.lng && !this.lat) {
        this.mapLoading = true;
        this.getCurrentPosition()
          .then((pos) => {
            this.lng = pos.lng;
            this.lat = pos.lat;
            this.radius = 1000;
            this.drawFenceCircle(pos);

            this.$emit("onUpdateMapData", {
              lng: this.lng,
              lat: this.lat,
              radius: this.radius,
            });

            this.mapLoading = false;
          })
          .catch((error) => {
            console.log(error);
          });
      } else {
        this.drawFenceCircle(mapService.getLngLat(this.lng, this.lat));
        this.$emit("onUpdateMapData", {
          lng: this.lng,
          lat: this.lat,
          radius: this.radius,
        });
      }
    },
    drawFenceCircle(fenceCenter) {
      if (this.fenceCircle) {
        this.fenceCircle.setCenter(mapService.getLngLat(this.lng, this.lat));
      } else {
        let options = {
          strokeColor: "#F33",
          strokeOpacity: 1,
          strokeWeight: 3,
          fillColor: "ee2200",
          fillOpacity: 0.35,
          enableEditing: true,
        };
        this.fenceCircle = AMap.invoke(
          "Circle",
          fenceCenter,
          this.radius * 1,
          options
        );
        AMap.invoke('centerAndZoom', fenceCenter, 14)
        AMap.invoke("addOverlay", this.fenceCircle);
        AMap.invoke("circleAddEventListener", "lineupdate", (e) => {
          let overlay = e.overlay;
          this.radius = parseInt(overlay.getRadius() / 1);
          this.lng = e.overlay.getCenter().lng;
          this.lat = e.overlay.getCenter().lat;
          this.$emit("onUpdateMapData", {
            lng: this.lng,
            lat: this.lat,
            radius: this.radius,
          });
        });
      }
    },
    initFence(data) {
      console.log(data)
      let _this = this;
      this._mapPromiseTimeout = setInterval(function () {
        if (_this.mapObj) {
          clearInterval(_this._mapPromiseTimeout);
          if (!data) {
            return false;
          }
          this.fenceType = data.fenceType;
          switch (data.fenceType) {
            case "area":
              _this.areaText = data.areaText;
              _this.drawArea();
              break;
            case "polygon":
              if (data.polygonPath && data.polygonPath.length) {
                _this.polygonPath = data.polygonPath;
              }
              _this.drawPolygon();
              break;
            default:
              _this.lng = data.lng;
              _this.lat = data.lat;
              _this.radius = data.radius;
              _this.drawFence();
              break;
          }
        }
      }, 100);
    },
    // 更新围栏信息
    updateFence(data) {
      console.log("更新围栏信息", data);
      let _this = this;
      let mapInterval = setInterval(function () {
        if (_this.mapObj) {
          clearInterval(mapInterval);
          AMap.invoke("clearOverlays");
          _this.fenceType = data.fenceType;

          if (_this.fenceType === "circle") {
            _this.fenceCircle = null;
            if (data.lng) {
              _this.lng = data.lng;
            }
            if (data.lat) {
              _this.lat = data.lat;
            }
            if (data.radius) {
              _this.radius = data.radius;
            }

            _this.drawFence();
          } else if (_this.fenceType === "area") {
            if (data.areaText) {
              _this.areaText = data.areaText;
            }
            if (_this.areaText) {
              _this.drawArea();
            }
          } else if (_this.fenceType === "polygon") {
            console.log()
            _this.drawPolygon();
          }
        }
      }, 100);
    },
    drawArea() {
      let _this = this;
      for (var i = 0, l = this.polygons.length; i < l; i++) {
        this.polygons[i].setMap(null);
      }
      _this.mapLoading = true;
      AMap.invoke("clearOverlays");
      if (this.dist) AMap.invoke("removeDistrictLayer", this.dist);
      this.dist = AMap.invoke("DistrictLayer", {
        name: `(${_this.areaText})`,
        fillOpacity: 0.7,
        fillColor: "#CCF3FF",
        strokeColor: "#CC66CC",
        viewport: true,
      });
      AMap.invoke("addDistrictLayer", this.dist);
      _this.mapLoading = false;
    },
    moveCenter() {
      this.lng = this.contextMenuPositon.lng;
      this.lat = this.contextMenuPositon.lat;
      if (this.fenceCircle) {
        AMap.invoke("circleDisableEditing");
        this.fenceCircle && this.fenceCircle.setCenter(this.contextMenuPositon);
        AMap.invoke("removeOverlay", this.fenceCircle);
        AMap.invoke("addOverlay", this.fenceCircle);
        AMap.invoke("circleEnableEditing");
      } else {
        const lnglat = mapService.getLngLat(this.lng, this.lat);
        this.drawFenceCircle(lnglat);
      }
    },
    getCurrentPosition() {
      const self = this;
      return new Promise((resolve, reject) => {
        AMap.invoke("Geolocation", (res) => {
          var lnglatXY = mapService.getLngLat(res.longitude, res.latitude);
          resolve(lnglatXY);
        });
      });
    },
    drawPolygon() {
      const self = this;
      console.log(this.polygonPath)
      if (this.polygonPath.length) {
        let options = {
          zIndex: 10,
          strokeColor: "#FF33FF",
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: "#1791fc",
          enableEditing: true,
        };
      
        self.polygon = AMap.invoke("Polygon", this.polygonPath, options);
        //获取多边形的中间位置
        let lnglat = self.polygon.getBounds().getCenter();
        // AMap.invoke("panTo", lnglat, true);
        AMap.invoke("centerAndZoom", lnglat, 14);
        AMap.invoke("polygonAddEventListener", "lineupdate", function (e) {
          let pathArr = self.polygon.getPath();
          self.emitPolyEvent(pathArr);
        });

        AMap.invoke("addOverlay", self.polygon);
        AMap.invoke('setZoom',17)
      } else {
        var styleOptions = {
          strokeColor: "#FF33FF", // 边线颜色
          fillColor: "#1791fc", // 填充颜色。当参数为空时,圆形没有填充颜色
          strokeWeight: 6, // 边线宽度,以像素为单位
          strokeOpacity: 0.2, // 边线透明度,取值范围0-1
          fillOpacity: 0.4, // 填充透明度,取值范围0-1
        };
        var labelOptions = {
          borderRadius: "2px",
          background: "#FF33FF",
          border: "1px solid #E1E1E1",
          color: "#703A04",
          fontSize: "12px",
          letterSpacing: "0",
          padding: "5px",
        };
        self.drawingManager = AMap.invoke(
          "DrawingManager",
          mapService.mapInstance,
          {
            isOpen: true, // 是否开启绘制模式
            enableDrawingTool: false,
            enableCalculate: false, // 绘制是否进行测距测面
            enableSorption: true, // 是否开启边界吸附功能
            sorptiondistance: 20, // 边界吸附距离
            circleOptions: styleOptions, // 圆的样式
            polylineOptions: styleOptions, // 线的样式
            polygonOptions: styleOptions, // 多边形的样式
            rectangleOptions: styleOptions, // 矩形的样式
            labelOptions: labelOptions, // label样式
          }
        );
        AMap.invoke(
          "drawingManagerAddEventListener",
          "polygoncomplete",
          function (e) {
            let overlays = e;
            let pathArr = e.getPath();
           
            // let resultArr = pathArr.map((item) => {
            //     return item.latLng
            // })
            self.emitPolyEvent(pathArr);
          }
        );
        AMap.invoke("setDrawingMode", "polygon");
      }
    },
    emitPolyEvent(resultArr) {
      this.polygonPath = resultArr;
      this.$emit("onUpdateMapData", {
        polygonPath: this.polygonPath,
      });
    },
    bindPolyEvent(polyEditor) {
      const self = this;
      polyEditor.on("addnode", function (event) {
        console.log("触发事件:addnode");
        self.emitPolyEvent();
      });

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

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

      polyEditor.on("end", function (event) {
        console.log("触发事件: end");
        self.emitPolyEvent();
        // event.target 即为编辑后的多边形对象
      });
    },
    transfer() {
      this.transferTimeoutId && window.clearTimeout(this.transferTimeoutId);
      this.transferTimeoutId = window.setTimeout(() => {
        const flag = new Date();
        this.transferFlag = flag;
        if (!this.geocoder) {
          mapService.getGeocoder().then((gc) => {
            this.geocoder = gc;
            this.getAddress(flag);
          });
        } else {
          this.getAddress(flag);
        }
      }, 500);
    },
    getAddress(flag) {
      const lnglatXY = [this.form.lng, this.form.lat];
      this.transferAddr = "";

      this.geocoder.getAddress(lnglatXY, (status, result) => {
        if (flag == this.transferFlag) {
          if (status === "complete" && result.info === "OK") {
            //获取地址成功
            this.form.transferAddr = result.regeocode.formattedAddress;
            this.$emit("onUpdateMapData", {
              lng: this.form.lng,
              lat: this.form.lat,
              address: this.form.transferAddr,
              radius: this.form.radius,
            });
          } else {
            this.form.transferAddr = "";
          }
        }
      });
    },
  },
  components: {
    FenceMapControll,
  },
};
</script>
<style scoped>
.fence-map {
  position: relative;
}
.fence-map .map-container {
  width: 100%;
  height: 500px;
}
.fence-map .map-seacrh-wrap {
  position: absolute;
  top: 40px;
  left: 10px;
  z-index: 1000;
}

.el-form-item {
  margin: -20px 0 20px 10px;
}
</style>
<style lang="scss">
.context_menu {
  min-width: 10em;
  background-color: #fff;
  padding: 10px;
  border: 1px solid #efefef;
  border-radius: 2px;
  cursor: pointer;
  & > p {
    margin: 0;
    i {
      font-size: 18px;
      color: #094;
      margin-right: 5px;
    }
    i,
    span {
      vertical-align: middle;
    }
  }
}
.tangram-suggestion-main {
  z-index: 9999 !important; /* 使用 !important 可以确保覆盖其他样式 */
}
</style>