uniapp打开地图选择位置

172 阅读1分钟

在项目中遇到一个要用户授权位置且可以用户自己选择位置的功能,看起来好像很难,其实并不难

实现代码

<template>
	<view>
		<view class="uni-padding-wrap">
			<view style="background:#FFFFFF; padding:40rpx;">
				<view class="uni-hello-text uni-center">当前位置信息</view>
				<block v-if="hasLocation === false">
					<view class="uni-h2 uni-center uni-common-mt">未选择位置</view>
				</block>
				<block v-if="hasLocation === true">
					<view class="uni-hello-text uni-center" style="margin-top:10px;">
						{{locationAddress}}
					</view>
					<view class="uni-h2 uni-center uni-common-mt">
						<text>{{location.longitude[0]}}°{{location.longitude[1]}}′</text>
						<text>\n{{location.latitude[0]}}°{{location.latitude[1]}}′</text>
					</view>
				</block>
			</view>
			<view class="uni-btn-v">
				<button type="primary" @tap="chooseLocation">选择位置</button>
				<button @tap="clear">清空</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				hasLocation: false,
				location: {},
				locationAddress: ''
			}
		},
		methods: {
			chooseLocation: function () {
				uni.chooseLocation({
					success: (res) => {
						this.hasLocation = true,
							this.location = this.formatLocation(res.longitude, res.latitude),
							this.locationAddress = res.address
					}
				})
			},
			clear: function () {
				this.hasLocation = false
			},
			formatLocation(longitude, latitude) {
				if (typeof longitude === 'string' && typeof latitude === 'string') {
					longitude = parseFloat(longitude)
					latitude = parseFloat(latitude)
				}
				longitude = longitude.toFixed(2)
				latitude = latitude.toFixed(2)
				return {
					longitude: longitude.toString().split('.'),
					latitude: latitude.toString().split('.')
				}
			}
		}
	}
</script>

如若转载,请注明出处:开源字节   sourcebyte.cn/article/249…