vueh5同步引入高德地图

331 阅读1分钟

``

<template>
	<scroll-view class="basicInfo" scroll-y="true">

		<view class="viewMap" id="container">
			<cover-view class="back" @click="back">
				<image src="../../static/image/back-map.png" class="pic"></image>
			</cover-view>

		</view>

	</scroll-view>
</template>


<script>
	import RemoGeoLocation from '../../utils/remoGeoLocation.js'
	import {
		similarNumInfo
	} from '../../api/approve'
	var map, marker, getLng, getLat, text, address;
	var addressObj = {
		address: ''
	}
	var approveData = {
		opinionId: '',
		approverNo: '',
		applierNo: ''
	}
	var title = '';
	var content = []
	window.mapInit = function() {

		//  初始化地图
		map = new AMap.Map('container', {
			zoom: 10,
			resizeEnable: true
		});

		map.on('complete', () => { //地图的生命周期点

			// 添加工具条
			AMap.plugin([
				'AMap.ToolBar',
			], function() {
				// 在图面添加工具条控件,工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
				map.addControl(new AMap.ToolBar({
					// 简易缩放模式,默认为 false
					liteStyle: true
				}));
			});


			// 定位当前位置样式

			var options = {
				showButton: true, //是否显示定位按钮
				buttonPosition: 'LB', //定位按钮的位置
				/* LT LB RT RB */
				buttonOffset: new AMap.Pixel(10, 20), //定位按钮距离对应角落的距离
				showMarker: true, //是否显示定位点
				markerOptions: { //自定义定位点样式,同Marker的Options
					offset: new AMap.Pixel(-18, -36),
					content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
				},
				showCircle: true, //是否显示定位精度圈
				circleOptions: { //定位精度圈的样式
					strokeColor: '#0093FF',
					noSelect: true,
					strokeOpacity: 0.5,
					strokeWeight: 1,
					fillColor: '#02B0FF',
					fillOpacity: 0.25
				},
				enableHighAccuracy: true, //是否使用高精度定位,默认:true
				timeout: 1000, //超过10秒后停止定位,默认:无穷大
				maximumAge: 0, //定位结果缓存0毫秒,默认:0
				convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
			}

			// 精准定位当前位置   
			AMap.plugin(["AMap.Geolocation"], function() {
				// try{
				// 	if (AMap.UA.ios) {
				// 		//使用远程定位,见 remogeo.js
				// 		var remoGeo = new RemoGeoLocation();
				// 		//替换方法
				// 		navigator.geolocation.getCurrentPosition = function() {
				// 			return remoGeo.getCurrentPosition.apply(remoGeo, arguments);
				// 		};
				// 		//替换方法
				// 		navigator.geolocation.watchPosition = function() {
				// 			return remoGeo.watchPosition.apply(remoGeo, arguments);
				// 		};
				// 	}
				// }catch(e){
				// 	console.log(e,"ios======error");
				// }

				var geolocation = new AMap.Geolocation(options);
				map.addControl(geolocation);
				geolocation.getCurrentPosition()


				AMap.event.addListener(geolocation, 'complete', (result) => {
					onComplete(result)

				});
				AMap.event.addListener(geolocation, 'error', function(result) {

					onError(result);

				});

			});




			// geolocation.getCurrentPosition(function(status, result) {
			// 		if (status == 'complete') {
			// 			onComplete(result)

			// 		} else {
			// 			console.log(result, "GPS定位出错result====")

			// 			//使用远程定位,置换navigator的API
			// 			var remoGeo = new RemoGeoLocation();
			// 			navigator.geolocation.getCurrentPosition = function() {
			// 				return remoGeo.getCurrentPosition.apply(remoGeo, arguments);
			// 			};
			// 			navigator.geolocation.watchPosition = function() {
			// 				return remoGeo.watchPosition.apply(remoGeo, arguments);
			// 			};

			// 			//重新初始化定位
			// 			map.removeControl(geolocation);
			// 			geolocation = new AMap.Geolocation(options);
			// 			map.addControl(geolocation);
			// 			geolocation.getCurrentPosition(function(status, result) {
			// 				if (status == 'complete') {
			// 					onComplete(result)

			// 				} else {
			// 					console.log(result, "IP定位出错result====")

			// 					onError(result);
			// 				}
			// 			});
			// 		}
			// 	});


			//解析定位结果
			function onComplete(data) {
				if (data) {

					if (addressObj.address !== undefined) {
						getLng = addressObj.getLng
						getLat = addressObj.getLat
						address = addressObj.address
					} else {
						getLng = data.position.lng
						getLat = data.position.lat
						address = data.formattedAddress
						addressObj.getLng = data.position.lng
						addressObj.getLat = data.position.lat
						addressObj.address = data.formattedAddress
					}
					console.log(addressObj.address, 'addressObj.address', getLng, addressObj.address)
					var circle = new AMap.Circle({
						center: new AMap.LngLat(data.position.lng, data.position.lat), // 圆心位置
						radius: 1000, //半径
						// 设置是否可以拖拽
						// draggable: true,
						strokeColor: "rgba(57, 123, 230, 0.2)", //线颜色
						strokeOpacity: 1, //线透明度
						strokeWeight: 3, //线粗细度
						fillColor: "rgba(57, 123, 230, 0.2)", //填充颜色
						fillOpacity: 0.35, //填充透明度

					});

					//定位标记物
					marker = new AMap.Marker({
						position: [getLng ? getLng : data.position.lng, getLat ? getLat : data.position
							.lat
						],
						icon: require("../../static/image/map.png"),
						offset: new AMap.Pixel(10, -20),
						// 设置是否可以拖拽
						draggable: true,
						cursor: 'move',
						// 设置拖拽效果
						raiseOnDrag: true
					});


					map.add(marker)
					map.add(circle);
					map.setFitView();
					content = []
					content.push(address ? address : data.formattedAddress)

					infoWindow.setContent(createInfoWindow(title, content.join("<br/>")))
					infoWindow.open(map, marker.getPosition());

					marker.on('dragend', markerDrag);
					marker.on('click', markerClick);
					marker.setMap(map);

					//拖拽出现信息弹框
					AMap.event.addListener(marker, 'dragend', function() {
						infoWindow.open(map, marker.getPosition());
					});

					//点击出现信息弹框
					AMap.event.addListener(marker, 'click', function() {
						console.log("点击")
						content = [];
						content.push(address)
						infoWindow.setContent(createInfoWindow(title, content.join("<br/>")))
						infoWindow.open(map, marker.getPosition());

					});
				}

				// uni.hideLoading()


			}
			//解析定位错误信息
			function onError(data) {

				uni.showModal({
					title: '提示',
					content: '定位失败',
					showCancel: false,
					buttonText: '知道了',
					confirmColor: '#00A57C', //字体的颜色
					success: function(res) {
						if (res.confirm) {
							// uni
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}

						if (navigator.geolocation) {
							navigator.geolocation.getCurrentPosition(e => {
								console.log(e, "navigator==e")
								uni.showToast({
									title: "请稍后再试",
									icon: 'none'
								})
							}, error => {
								if (error.code === 1) {
									uni.showToast({
										title: "请检查是否已打开定位",
										icon: 'none'
									})
								} else if (error.code === 2) {
									uni.showToast({
										title: "请打开手机定位",
										icon: 'none'
									})
								}

								console.log(error, "navigator==error")
							});


						} else {
							uni.showToast({
								title: "请检查是否已打开定位",
								icon: 'none'
							})
						}
					}
				});
			}


			//经纬度地理位置转换

			function getPositionByLonLats(lng, lat) {

				var lnglatXY = [lng, lat]; // 地图上所标点的坐标
				AMap.service('AMap.Geocoder', function() { // 回调函数
					let geocoder = new AMap.Geocoder({});
					geocoder.getAddress(lnglatXY, function(status, result) {
						if (status === 'complete' && result.info === 'OK') {

							address = result.regeocode.formattedAddress;
							content = [];
							content.push(address)
							addressObj.address = address
							infoWindow.setContent(createInfoWindow(title, content.join(
								"<br/>")))

						} else {

						}
					});
				});
			}


			// 拖拽结束获取经纬度
			const markerDrag = (e) => {
				text = `${e.lnglat.getLng()},${e.lnglat.getLat()} `
				getPositionByLonLats(e.lnglat.getLng(), e.lnglat.getLat())
				addressObj.getLng = e.lnglat.getLng()
				addressObj.getLat = e.lnglat.getLat()
			}
			// 点击获取经纬度
			const markerClick = (e) => {
				console.log(e, 'e')
				text = `${e.lnglat.getLng()},${e.lnglat.getLat()} `
				getPositionByLonLats(e.lnglat.getLng(), e.lnglat.getLat())
				//getLng()代表经度的值
				//getLat()代表纬度的值
				addressObj.getLng = e.lnglat.getLng()
				addressObj.getLat = e.lnglat.getLat()

			}


			//初始化信息框

			var infoWindow = new AMap.InfoWindow({
				isCustom: true, //使用自定义窗体
				content: createInfoWindow(title, content.join("<br/>")),
				offset: new AMap.Pixel(16, -25),

			});




			//构建自定义信息窗体
			function createInfoWindow(title, content) {

				var info = document.createElement("div");
				// 定义中部内容
				var middle = document.createElement("div");
				middle.className = "info-middle";
				let containerS = document.createElement("div");
				let confirm = document.createElement("div");
				let line = document.createElement("div");
				containerS.className = "info-middle-containerS";
				confirm.className = "info-middle-confirm";
				containerS.innerHTML = content;
				confirm.innerHTML = '确定'
				line.innerHTML = "|";
				confirm.onclick = closeInfoWindow;
				middle.appendChild(containerS);
				middle.appendChild(line);
				middle.appendChild(confirm);
				info.appendChild(middle);
				return info;
			};



			//关闭信息窗体

			function closeInfoWindow() {
				let obj = {
					longitude: addressObj.getLng, //经度
					latitude: addressObj.getLat //纬度

				}
				map.remove(marker)

				similarNumInfo(obj).then((res) => {
					if (res.code == '000000' && res.data && res.data.length > 0) {
						uni.showModal({
							title: '提示',
							content: '当前位置附近100米内近30天已有申请记录',
							// showCancel: false,
							confirmText: '知道了',
							confirmColor: '#00A57C', //字体的颜色
							success: function(res) {
								if (res.confirm) {

									if (approveData.opinionId) {
										uni.$emit('detailMap', {
											addressObj: encodeURIComponent(JSON
												.stringify(
													addressObj)),
											opinionId: approveData.opinionId,
											approverNo: approveData.approverNo,
											applierNo: approveData.approveData,
											flowId: approveData.flowId,
											returnStatus: approveData.returnStatus,
											status: approveData.status,
											init: false,
											title: "新增申请"
										})


										// uni.redirectTo({
										// 	url: '/pages/addApply/addApply?addressObj=' +
										// 		encodeURIComponent(JSON.stringify(
										// 			addressObj)) + '&opinionId=' + approveData
										// 		.opinionId + '&approverNo=' + approveData
										// 		.approverNo + '&applierNo=' + approveData
										// 		.applierNo + '&flowId=' + approveData.flowId +
										// 		'&returnStatus=' + approveData.returnStatus +
										// 		'&status=' + approveData.status + '&init=false'
										// })
									} else {

										uni.$emit('detailMap', {
											addressObj: encodeURIComponent(JSON
												.stringify(
													addressObj)),
											init: false,
											title: "新增申请"
										})


										// uni.redirectTo({
										// 	url: '/pages/addApply/addApply?addressObj=' +
										// 		encodeURIComponent(JSON.stringify(
										// 			addressObj)) + '&init=false'
										// })
									}


									uni.navigateBack({
										delta: 1
									});

									map.clearInfoWindow();
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} else if (res.code == '000000') {
						if (approveData.opinionId) {
							uni.$emit('detailMap', {
								addressObj: encodeURIComponent(JSON.stringify(addressObj)),
								opinionId: approveData.opinionId,
								approverNo: approveData.approverNo,
								applierNo: approveData.approveData,
								flowId: approveData.flowId,
								returnStatus: approveData.returnStatus,
								status: approveData.status,
								init: false,
								title: "新增申请"
							})

							// uni.redirectTo({
							// 	url: '/pages/addApply/addApply?addressObj=' + encodeURIComponent(JSON
							// 			.stringify(addressObj)) + '&opinionId=' + approveData.opinionId +
							// 		'&approverNo=' + approveData.approverNo + '&applierNo=' + approveData
							// 		.applierNo + '&flowId=' + approveData.flowId + '&returnStatus=' +
							// 		approveData.returnStatus + '&status=' + approveData.status +
							// 		'&init=false'
							// })
						} else {
							uni.$emit('detailMap', {
								addressObj: encodeURIComponent(JSON.stringify(addressObj)),
								init: false,
								title: "新增申请"
							})
							// uni.redirectTo({
							// 	url: '/pages/addApply/addApply?addressObj=' + encodeURIComponent(JSON
							// 		.stringify(addressObj)) + '&init=false'
							// })
						}

						uni.navigateBack({
							delta: 1
						});
					};
				})





			}


		});


	};

	export default {

		data() {
			return {}
		},
		onLoad: function(option) {
			this.$swicthToNativeApp("setTitle", "地图")
			if (option.addressObj.address !== '') {
				addressObj = JSON.parse(decodeURIComponent(option.addressObj));
				addressObj.getLng = addressObj.getLng
				addressObj.getLat = addressObj.getLat
				addressObj.address = addressObj.address
			}
			if (option.opinionId) {
				approveData.opinionId = option.opinionId
			}
			if (option.applierNo) {
				approveData.applierNo = option.applierNo
			}
			if (option.approverNo) {
				approveData.approverNo = option.approverNo
			}
			if (option.returnStatus) {
				approveData.returnStatus = option.returnStatus
			}
			if (option.status) {
				approveData.approverNo = option.status
			}
			if (option.flowId) {
				approveData.flowId = option.flowId
			}
			this.loadScrpit()

		},
		onUnload() {
			uni.$emit('detailMap', {
				addressObj: encodeURIComponent(JSON.stringify(addressObj)),
				init: false,
				title: "新增申请"
			})
		},


		methods: {
			loadScrpit() {
				var script = document.createElement('script');
				script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=7fe4a8518ec437cc8bc7e0e0e6cf910e&callback=mapInit';
				document.body.appendChild(script);

			},

			back() {
				map.clearInfoWindow();

				uni.navigateBack({
					delta: 1
				});

				// if (approveData.opinionId) {

				// 	uni.$emit('detailMap', {
				// 		addressObj:encodeURIComponent(JSON.stringify(addressObj)),
				// 		init: false,
				// 	})

				// 	// uni.redirectTo({
				// 	// 	url: '/pages/addApply/addApply?addressObj=' + encodeURIComponent(JSON.stringify(
				// 	// 			addressObj)) + '&opinionId=' + approveData.opinionId +
				// 	// 		'&approverNo=' + approveData.approverNo +
				// 	// 		'&applierNo=' + approveData.applierNo + '&flowId=' + approveData.flowId + '&status=' +
				// 	// 		approveData.status + '&init=false' + '&returnStatus=' +
				// 	// 		approveData.returnStatus
				// 	// })
				// } else {

				// 	uni.$emit('detailMap', {
				// 		addressObj:encodeURIComponent(JSON.stringify(addressObj)),
				// 		init: false,
				// 	})

				// 	// uni.redirectTo({
				// 	// 	url: '/pages/addApply/addApply?addressObj=' + encodeURIComponent(JSON.stringify(
				// 	// 		addressObj)) + '&init=false'
				// 	// })
				// }

			},


		}
	}
</script>
<style lang="scss" scoped>
	.back {
		position: fixed;
		left: 10rpx;
		top: 30rpx;
		z-index: 999;

		.pic {
			width: 104rpx;
			height: 76rpx;
		}
	}


	.viewMap {
		width: 750rpx;
		height: 1334rpx;
		background: #D8D8D8;
		border-radius: 12rpx;

		.map {
			width: 100%;
			height: 100%;
		}

	}

	/deep/ .info-middle {
		width: 600rpx;
		height: 100rpx;
		border-radius: 90rpx;
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		background: #FFF;

		.info-middle-containerS {
			width: 500rpx;
		}

		.info-middle-confirm {
			width: 90rpx;
			color: #00A57C;
			margin-left: 10rpx;
		}
	}

	/deep/.info-middle:after {
		border: 10rpx solid transparent;
		border-top: 15rpx solid #fff;
		position: absolute;
		content: "";
		left: 50%;
		margin-left: 10rpx;
		top: 90%;
	}

	.main {
		width: 670rpx;
		height: 710rpx;
		background: #FFF;
		border-radius: 24rpx;
	}

	/deep/ .amap-geo {
		right: 220rpx;
		bottom: 30rpx;
	}
</style>