微信小程序获取当前城市定位的简单demo

用uniapp写小程序实现简单的获取当前城市定位的demo

先上代码

<template>
	<view>
		{{currentCity || '广州'}}
	</view>
</template>

<script>
	var QQMapWX = require('../../static/js/qqmap-wx-jssdk.min.js');
	export default {
		data() {
			return {
				currentCity:''
			}
		},
		onReady(){
			this.getCity()
		},
		methods: {
			getCity(){
					// console.log(uni)
					let that = this;
					// 获取用户权限
					uni.authorize({
						scope:"scope.userLocation",	
						success(){
							// 引入腾讯地图api
							let qqmapsdk = new QQMapWX({
								key:'RAQBZ-ELHLJ-XSHFY-KZYPD-B7PCO-EFF2W'
							});
							// 获取定位信息
							uni.getLocation({
								type:'gcj02',
								success(res){
									// console.log(res.longitude);
									// console.log(res.latitude);
									// 逆地址解析
									qqmapsdk.reverseGeocoder({
										location:{
											latitude: res.latitude,
											longitude: res.longitude
										},
										success(res){
											that.currentCity = res.result.address_component.city;
											console.log(that.currentCity)
										}
									})
								}
							})
						},
						fail(err){
							console.log(err)
						}
					})
					
				}
			}
		}
</script>

<style>

</style>

首先需要获取用户权限 uni.authorize

在这里插入图片描述附上文档地址

同时要开启位置接口配置

在这里插入图片描述

其次获取定位信息 uni.getLocation

在这里插入图片描述
附上官方文档

使用的是腾讯地图api

需要下载微信小程序JavaScriptSDK才能使用,腾讯地图文档中有详细介绍 官方文档

发布了6 篇原创文章 · 获赞 0 · 访问量 425

猜你喜欢

转载自blog.csdn.net/Xyouzi/article/details/104033300