fenceMapModal.vue 10 KB
<template>
    <!-- 围栏调用地图弹框 -->
	<el-dialog id="fenceMapModal"  :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">

        	<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>

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

		  	<div class="map-seacrh-wrap">
		  		<!-- <input type="text" id="fenceMapSearch"> -->
		  		<el-input placeholder="请输入位置" id="fenceMapSearch" size="small" v-model="fenceMapSearch">
		  			<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 {services} from '../../api'
import remoteLoad from 'utils/remoteLoad.js'
import mapService from 'utils/mapService.js'
import MapControll from './MapControll.vue'
const BUSINESS_SERVICE =  services.business;
import {CONSTANT} from '../../constant'

export default{
	props: ['fenceMapModalVisible', 'mapData', 'init'],
	data(){
		let checkLng = (rule, vaule, cb)=>{
			if(!/^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/.test(this.form.lng)){
				cb(new Error('请输入正确的格式'))
			}else{
				cb();
			}
		} 

		let checkLat = (rule, vaule, cb)=>{
			if(!/^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/.test(this.form.lat)){
				cb(new Error('请输入正确的格式'))
			}else{
				cb();
			}
		} 

		let checkTransferAddr = (rule, vaule, cb)=>{
			
			if(this.transferError){
				cb(new Error('所填经纬度不能正确解析地址,请重新输入'))
			}else if(!this.form.transferAddr){
				cb(new Error('经纬度解析地址不能为空'))
			}else{
				cb()
			}
			
		} 
		let checkRadius = (rule, vaule, cb)=>{
			if(!/^(\d+|\d+\.\d{0,3})$/.test(this.form.radius)){
				cb(new Error('数字,精确到小数点后三位'))
			}else{
				cb();
			}
		} 

		return {
			fenceMapSearch: '',
			geolocation: null,
			circleEditor: null,
			circle: null,
			form: {
				lng: '',
				lat: '',
				transferAddr: '',
				radius: 1
			},
			transferTimeoutId: undefined,
			geocoder: null,
			transferFlag: null,

			rules: {
				lng: [
					{validator: checkLng, trigger: 'blur'}
				],
				lat: [
					{validator: checkLat, trigger: 'blur'}
				],
				transferAddr: [
					{validator: checkTransferAddr, trigger: 'blur'}
				],
				radius: [
					{validator: checkRadius, trigger: 'blur'}
				]
			},

			transferError: false
		}
	},
	mounted(){
		
	},
	watch: {
		lng(newVal){
			//this.transfer()
		},
		lat(newVal){
			//this.transfer()
		}
	},
	async created () {
		if(window.AMap){
			
		}else{
	      await remoteLoad(`${CONSTANT.AMAP_URL}`);
	      //this.initMap()
	    }
	},
	methods: {
		sure(){
			this.$refs.fenceMapForm.validate((valid)=>{
				if(valid){
					this.$emit('onFenceMapModalChange', false);
					
					this.$emit('onUpdateMapData',{
						lng: this.form.lng,
						lat: this.form.lat,
						address: this.form.transferAddr,
						radius: this.form.radius
					});

				}else{
					return false;
				}
			})
		},
		initMap(){
			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.bindSearch();
			      		this.drawFence()
					}else{
						this.checkMapLoaded = check()
					}
			    }, 100)
			}
			this.checkMapLoaded = check();
		},
		openDialog(){
			
			this.form.lng = this.mapData.lng
			this.form.lat = this.mapData.lat
			this.form.transferAddr = this.mapData.address
			this.form.radius = this.mapData.radius?this.mapData.radius:1
			
			
			//this.$emit('onFenceMapModalChange', true)
			if(this.mapObj){
				this.updateFence();
			}else{
				this.initMap()
			}
		},
		closeDialog(){
			this.$emit('onFenceMapModalChange', false)
		},
		bindSearch(){
			this.auto = new AMap.Autocomplete({
      			input: 'fenceMapSearch'
      		});

			this.autoCenterMarker = new AMap.Marker({
	            icon: require('images/auto-center-marker.gif'),
	            map: this.mapObj,
	            offset: new AMap.Pixel(-12,-12),
	            visible: false
	        });

      		AMap.event.addListener(this.auto, 'select', (e)=>{
      			if(e.poi && e.poi.location){
      				//this.mapObj.setZoom(15);
      				//this.mapObj.setCenter(e.poi.location)
      				//this.circle.setCenter(e.poi.location);
      				//this.mapObj.setCenter(e.poi.location);

      				this.autoCenterMarker.setPosition(e.poi.location);
      				this.autoCenterMarker.show();
      				mapService.setFitView()
      				this.fenceMapSearch = '';
      				this.form.lng = e.poi.location.lng;
					this.form.lat = e.poi.location.lat;
      			}
      		});
		},
		drawFence(){
			this.circleEditor && this.circleEditor.destroy();
			const mapObj = this.mapObj;
			let circleCenter = null;

			if(this.form.transferAddr){
				circleCenter = mapService.getLngLat(this.form.lng, this.form.lat)
			}else{

				circleCenter = mapObj.getCenter();
				this.form.lng = circleCenter.lng;
				this.form.lat = circleCenter.lat;
				this.transfer()
			}
			
            this.circle = new AMap.Circle({
			    map: mapObj,
			    center: circleCenter,
			    radius: this.form.radius*1000,
			    strokeColor: "#F33",
			    strokeOpacity: 1,
			    strokeWeight: 3,
			    fillColor: "ee2200",
			    fillOpacity: 0.35
			}); 

			mapObj.plugin(["AMap.CircleEditor"],()=>{ 
			    this.circleEditor = new AMap.CircleEditor(mapObj, this.circle); 

			    AMap.event.addListener(this.circleEditor, 'adjust', (e)=>{
			    	this.form.radius = e.radius/1000;
			    	this.$refs.fenceMapForm.validateField('radius');
			    });

			    AMap.event.addListener(this.circleEditor, 'move', (e)=>{
			    	this.form.lng = e.lnglat.lng;
			    	this.form.lat = e.lnglat.lat;
			    	this.transfer()
			    });

			    this.circleEditor.open(); 
			});
	        
	        mapService.setFitView()
	        mapObj.setZoom(14);
			
		},
		updateFence(){
			this.$refs.fenceMapForm.validateField('radius', (error)=>{
				if(!error){
					this.circle.setRadius(this.form.radius*1000);
					if(!this.transferError){

						if(this.form.transferAddr){
							let center = mapService.getLngLat(this.form.lng, this.form.lat);
							console.log(center)
							this.circle.setCenter(center);
						}else{
							const circleCenter = this.mapObj.getCenter();
							this.circle.setCenter(circleCenter);
							this.form.lng = circleCenter.lng;
							this.form.lat = circleCenter.lat;
							this.transfer()
						}

						
						

						mapService.setFitView()
			        	this.mapObj.setZoom(14);
					}
				}
			});
			
			
		},
		search(){

			this.auto&&AMap.event.trigger(this.auto, 'select')
		},
		validateLngLat(){
			let pass = true;
			this.$refs.fenceMapForm.validateField('lng', (error)=>{
				if(error){
					pass = false;
				}
			});
			this.$refs.fenceMapForm.validateField('lat', (error)=>{
				if(error){
					pass = false;
				}
			});
			return pass;
		},
		transfer(){
			if(this.form.lng && this.form.lat && this.validateLngLat()){
				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.transferError = false;
                        this.$refs.fenceMapForm.validateField('transferAddr');
                    }else{
                    	this.form.transferAddr = '';
                        this.transferError = true;
                        this.$refs.fenceMapForm.validateField('transferAddr');
                    }
                }
            });
		},
		refreshMap(){

		}
		
    },
	components:{
		MapControll
	}
}
</script>
<style scoped>
	.fence-map{
		position: relative;
	}
	.fence-map .map-container{
		width: 100%;
		height: 600px;
	}
	.fence-map .map-seacrh-wrap{
		position: absolute;
		top: 40px;
		left: 10px;
		z-index: 1000;
	}
	
	.el-form-item{
		margin: -20px 0 20px 10px;
	}
	
</style>