uniapp项目 封装地图定位组件

113 阅读1分钟

开始前先在配置文件manifest.json中找到 mp-weixin 的配置项,然后加上下面的配置

"permission": {
		  "scope.userLocation": {
		    "desc": "你的位置信息将用于小程序位置接口的效果展示"
		  }
		},
"requiredPrivateInfos": ["getLocation", "chooseLocation"]

组件代码:

<template>
	<view class="page-map">
		<div class="show-position"></div>
		<map
			style="width: 100%; height: 100vh"
			:longitude="curLongitude"
			:latitude="curLatitude"
			:show-location="true"
			id="myMap"
		/>
		<div class="tool-box">
			<div class="tool-item" @click="getUserLocation">定位</div>
			<div class="tool-item" @click="searchLocation">搜索</div>
		</div>
	</view>
</template>

<script setup>
	import { ref, onMounted, computed, watchEffect, getCurrentInstance } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	const { proxy } = getCurrentInstance();
	const example = proxy;

	let mapContext = null; // 地图上下文
	onMounted(() => {
		getUserLocation();
		mapContext = uni.createMapContext('myMap', example);
	});

	let curLongitude = ref(''); // 经度
	let curLatitude = ref(''); // 纬度
	let selectedLocation = ref(null); // 选中的位置信息
	// 获取地理位置
	function getUserLocation() {
		uni.getLocation({
			isHighAccuracy: true,
			success: (res) => {
				console.log('经度', res.longitude, '纬度', res.latitude);
				curLongitude.value = res.longitude;
				curLatitude.value = res.latitude;
				mapContext.moveToLocation({
					longitude: res.longitude,
					latitude: res.latitude,
				});
				uni.showToast({
					title: '已经来到当前所处位置',
					icon: 'none',
				});
			},
			fail: (err) => {
				console.error(err);
			},
		});
	}
	// 搜索位置
	function searchLocation() {
		uni.chooseLocation({
			success: (res) => {
				console.log('地址信息', res);
				selectedLocation.value = {
					longitude: res.longitude,
					latitude: res.latitude,
					name: res.name,
					address: res.address,
				};
				curLongitude.value = res.longitude;
				curLatitude.value = res.latitude;
				mapContext.moveToLocation({
					longitude: res.longitude,
					latitude: res.latitude,
				});
				uni.showToast({
					title: '已经来到' + selectedLocation.value.name,
					icon: 'none',
				});
			},
			fail: (err) => {
				console.log('失败', err);
			},
		});
	}
</script>

<style lang="scss" scoped>
	.show-position {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		box-shadow: 0 0 10px 10px rgba(170, 150, 218, 0.5);
		background: #a8d8ea;
		z-index: 999;
	}
	.tool-box {
		position: fixed;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
		background: #a8d8ea;
		border-radius: 10rpx;
		z-index: 999;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		.tool-item {
			width: 100%;
			height: 50rpx;
			background: #ffffff;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28rpx;
			font-weight: 700;
			margin: 10rpx 0;
		}
	}
</style>