1. 程式人生 > 實用技巧 >微信小程式首頁定位

微信小程式首頁定位

使用uni-app開發微信小程式.
之前在app.js定位,然後傳給首頁,這樣獲取不到值,就把定位程式碼寫在了首頁.

<template>
	<view class="content">
		<view class="">
			定位地址:{{city}}
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				locationStatus:false,//是否定位過
				city:'定位中...'
			}
		},
		onShow() {
			// 判斷是否定位過,如果沒有定位,就執行定位
			if(this.locationStatus==false){
				this.dingwei()
				uni.setStorageSync('locationStatus',true)
				this.locationStatus=uni.getStorageSync('locationStatus')
			}else{ //若定位過,直接把本地的定位地址賦值
				this.city=uni.getStorageSync('city')
			}
			
		},
		onLoad() {
		},
		
		methods: {
			// 開啟設定
			openConfirm(){
				uni.showModal({
					title: '請求授權當前位置',
					content: '需要獲取您的地理位置,請確認授權',
					success:(res=>{
						if(res.confirm){
							uni.openSetting();// 開啟地圖許可權設定
						}else if(res.cancel){
							uni.showToast({
								title: '你拒絕了授權,無法獲得周邊資訊',
								icon: 'none',
								duration: 1000                            
							})
						}
					}) 
				})
			},
			// 定位
			dingwei(){
				var that = this
				// 授權
				uni.authorize({
				    scope: 'scope.userLocation',
				    success() {
						// 定位
				       uni.getLocation({
				           type: 'gcj02',
				           success: function (res) {
				               console.log('當前位置的經度:' + res.longitude);
				               console.log('當前位置的緯度:' + res.latitude);
				       		var longitude = res.longitude
				       		var latitude= res.latitude
				       		var location = latitude+','+longitude
				       		console.log(location)
							// 逆解析地址 個人祕鑰
				       		wx.request({
				       		    url: 'https://apis.map.qq.com/ws/geocoder/v1/?key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1',
				       			data:{
				       				location:location
				       			},
				       			method: "get",
				       		    success: (res) => {
				       		        console.log(res.data.result.address);
									uni.setStorageSync('city',res.data.result.address)
									that.city=uni.getStorageSync('city')
				       		    }
				       		});
				           }
				       });
				    },
					fail(){    // 拒絕授權
						that.openConfirm();
						console.log("你拒絕了授權,無法獲得周邊資訊")
					}
				})
			}
		}
	}
</script>

<style>
</style>