新聞動態(tài)

位置:首頁 新聞動態(tài) 常見問題

uni-app微信小程序地圖獲取當前位置完整案例

新聞動態(tài)
2022年02月22日 閱讀:3012次

首先需要在配置文件中進行配置授權提示 點擊源碼視圖 添加下面代碼

/* 小程序特有相關 */
    "mp-weixin" : {
        "appid" : "wxda33332553aa5",
        "setting" : {
            "urlCheck" : false
        },
	"permission" : {
	    "scope.userLocation" : {
		"desc" : "您的位置將用于綁定您的區(qū)域"
	    }
	},
        "usingComponents" : true
    },

主要添加

"permission" : {
	    "scope.userLocation" : {
		"desc" : "您的位置將用于綁定您的區(qū)域"
	    }
},

如果獲取當前位置需要多次使用可以封裝在公共js文件中

//網絡請求
	map: function() {
		//對參數(shù)進行處理
		return new Promise((reslove, reject) => {
			uni.chooseLocation({
					success:(res)=> {
					reslove(res);
					},
					fail:()=>{
						uni.getSetting({
							success: (res) => {
								var status = res.authSetting;
								if(!status['scope.userLocation']){
									uni.showModal({
										title:"是否授權當前位置",
										content:"需要獲取您的地理位置,請確認授權,否則地圖功能將無法使用",
										success:(tip)=>{
											if(tip.confirm){
												uni.openSetting({
													success:(data)=>{
													
														if(data.authSetting['scope.userLocation']===true){
															uni.showToast({
																title:"授權成功",
																icon:"success",
																duration:1000
															})
															uni.chooseLocation({
																success: (res) => {
															reslove(res);
																	// this.getRegionFn(res);
																}
															})
														}else{
															uni.showToast({
																title:"授權失敗",
																icon:"none",
																duration:1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title:"調用授權窗口失敗",
									icon:"none",
									duration:1000
								})
							}
						})
					}
				});
		});
	},
	

頁面調用

<view @click="chooseLocation" class="iconfont icon-daohang"> </view>
//獲取位置
chooseLocation(){
	this.helper.map().then(res => {
		this.homeAddressStreet=res.address
		this.latitude=res.latitude
		this.name=res.name
		this.longitude=res.longitude	
	});
},

上一篇

下一篇