device-position.vue 2.41 KB
<template>
	<view class="map">
		<map
			id="my-map"
			ref="my-map"
			class="my-map"
			:style="{ height: allScreen - 44 + 'px' }"
			:latitude="myLatitude"
			:longitude="myLongitude"
			:markers="makers"
			enable-3D="true"
			show-compass="true"
			show-location="true"
		></map>
	</view>
</template>

<script>
const amapFile = require('@/config/amap-wx.js');
import { gdMapRequiredKey } from '@/config/gdMapConfig.js';

export default {
	data() {
		return {
			mapContext: null,
			allScreen: '',
			myLatitude: 0, //纬度
			myLongitude: 0, //经度
			makers: [
				{
					id: 1,
					latitude: 0,
					longitude: 0,
					iconPath: '../../static/location.png',
					width: '50px',
					height: '50px'
				}
			]
		};
	},
	onShow(){
		this.$nextTick(()=>{
			uni.setNavigationBarTitle({
				title:this.$t('menu.deviceLocation')
			})
		})
	},
	onLoad(e) {
		let params = null;
		if (e.data !== null) {
			params = JSON.parse(e.data);
		}
		let that = this;
		var myAmapFun = new amapFile.AMapWX({ key: gdMapRequiredKey });
		that.getMyLocation(params.longitude, params.latitude);
		uni.getSystemInfo({
			success: function(e) {
				that.allScreen = e.screenHeight;
			}
		});
	},
	onReady: function(res) {
		this.mapContext = uni.createMapContext('my-map', this);
	},
	methods: {
		getMyLocation(eLong, eLat) {
			let that = this;
			const newPos = this.bd_decrypt(eLong, eLat);
			that.myLatitude = newPos.lat;
			that.myLongitude = newPos.lng;
			that.makers[0].longitude = newPos.lng;
			that.makers[0].latitude = newPos.lat;
			if (newPos.lng == undefined || newPos.lat == undefined) {
				//如果没有位置信息则使用当前定位
				getLocationFunc();
			}
			const getLocationFunc = () =>
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						that.myLatitude = res.latitude;
						that.myLongitude = res.longitude;
					}
				});
		},
		//服务端返回的是百度地图坐标系,百度地图坐标系转换为高德地图坐标系(重要,不然会造成位置误差)
		bd_decrypt(bd_lng, bd_lat) {
			var X_PI = (Math.PI * 3000.0) / 180.0;
			var x = bd_lng - 0.0065;
			var y = bd_lat - 0.006;
			var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
			var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
			var gg_lng = z * Math.cos(theta);
			var gg_lat = z * Math.sin(theta);
			return { lng: gg_lng, lat: gg_lat };
		}
	}
};
</script>

<style scoped>
.my-map {
	width: 750rpx;
}
</style>