1、在获取定位之前需要申请开发者密钥 - - - - - -腾讯位置服务 - 立足生态,连接未来

2、在需要获取定位的项目文件夹中找到 manifest.json 文件 →→→ H5配置,输入申请的密钥

 就可以开始实操了!上代码

<template>
	<view>
		<button type="default" @click="getCurrentLocation()">获取当前位置</button>
		<button type="primary" @click="getaddress()">获取选择的位置</button>
		<view style="color: red;">
			{{positionInfo.address}}
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				positionInfo: {
					address: '',
					longitude: '', //经度
					latitude: '', //纬度
				},

			}
		},
		methods: {
			// 通过自带的方法获取到当前的经纬度,调用方法获取到地址获取到地址的中文信息
			getCurrentLocation() {
				let that = this //在uniapp中药定义一下this才能使用
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						console.log(res)
						that.positionInfo.longitude = res.longitude;
						that.positionInfo.latitude = res.latitude;
						that.loAcquire(that.positionInfo.longitude,         that.positionInfo.latitude)
					}
				});
			},
			// 获取当前地址
			loAcquire(longitude, latitude) {
				let that = this;
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let str = `output=jsonp&key='此处输入你申请的密钥'=${latitude},${longitude}` //记得在这里要输入密钥哦!
				this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/?' + str, {}).then(res => {
					console.log(res);
					uni.hideLoading();
					if (res.status == 0) {
						that.positionInfo.address = '当前位置是:' + res.result.address_component.street_number; //当前定位
					}
				})
			},
			// 获取选择地址
			getaddress() {
				let that = this
				uni.chooseLocation({
					success: function(res) {
						that.positionInfo.address = '选择的位置是:' + res.name
					}
				});
			},
		}
	}
</script>

<style scoped>
	button,
	view {
		margin: 20px;
	}
</style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐