详见:码云小程序demo1
1.wxml
<van
-cell
-group
>
{{address
}}
<!-- autosize
:自适应 获取授权,获取经纬度
-->
<van
-field autosize type
="textarea" model
:value
="{{ s_address }}"
center clearable label
="短信验证码"
placeholder
="请输入短信验证码" border
="{{ false }}" use
-button
-slot
>
<van
-button custom
-style
="width:100rpx" slot
="button" size
="small"
type
="primary" icon
="location-o"
bindtap
="getAddress3"></van
-button
>
</van
-field
>
<!--获取授权,打开地图选择位置
-->
<van
-field autosize type
="textarea" model
:value
="{{ r_address }}"
center clearable label
="短信验证码"
placeholder
="请输入短信验证码" border
="{{ false }}" use
-button
-slot
>
<van
-button custom
-style
="width:100rpx" slot
="button" size
="small"
type
="primary" icon
="location-o"
bindtap
="chooseAddress3"></van
-button
>
</van
-field
>
</van
-cell
-group
>
2.js
import Router
from '../../utils/index'
import {
$getLocation
,
$chooseLocation
} from '../../utils/location'
Router({
data
: {
s_address
: '',
r_address
: '',
},
async chooseAddress3() {
let res
= await $chooseLocation()
this.$
set('r_address', res
)
},
async getAddress3() {
let res
= await $getLocation()
console
.log(res
);
if (res
) {
let address
= await this.$
get('https://apis.map.qq.com/ws/geocoder/v1/', {
location
: [res
.lat
, res
.lng
].join(),
key
: 'K2VBZ-IM5WO-V65W7-SV4SA-W4HYF-VSFD3'
})
this.$
set('s_address', address
.result
.address
+
address
.result
.formatted_addresses
.recommend
)
}
},
}
3.封装的 $getLocation和$chooseLocation
import {
$msg
} from './index'
import {
getSetting
,
openSetting
} from './setting'
export let $getLocation = () => fixedSetting(getLocation
)
export let $chooseLocation = () => fixedSetting(chooseLocation
)
async function fixedSetting(callback
) {
let res
= await getSetting('scope.userLocation')
if (res
|| res
=== undefined
) {
return await callback()
} else {
let res1
= await openSetting('scope.userLocation')
if (res1
) {
return await callback()
} else
$msg("为了不影响您的使用,请授权定位")
}
}
function getLocation() {
return new Promise((resolve
) => {
wx
.getLocation({
success({
longitude
: lng
,
latitude
: lat
}) {
resolve({
lng
,
lat
});
},
fail
: () => $msg("为了不影响您的使用,请授权定位")
})
})
}
function chooseLocation() {
return new Promise((resolve
) => {
wx
.chooseLocation({
success({
address
,
name
}) {
resolve(
address
+ name
)
},
fail
: () => $msg("为了不影响您的使用,请授权定位")
})
})
}
4.独立的setting :获取目前请求过的权限和打开设置页
export function getSetting(permission
) {
return new Promise((resolve
) => {
wx
.getSetting({
success
: (res
) => {
resolve(res
.authSetting
[permission
])
}
})
})
}
export function openSetting(permission
) {
return new Promise((resolve
) => {
wx
.openSetting({
success
: (res
) => {
resolve(res
.authSetting
[permission
])
}
})
})
}
5.根目录json权限代码
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
转载请注明原文地址:https://tech.qufami.com/read-20403.html