详见:码云小程序demo1
1. wxml:
< button bindtap= "getAddress3" > 获取定位< / button>
2. js
import Router from '../../utils/index'
import {
getLocationWithSetting
} from '../../utils/location'
Router ( {
async getAddress3 ( ) {
let res = await getLocationWithSetting ( )
console. log ( res) ;
} ,
}
3. 封装的utils/ location getLocationWithSetting
import {
$msg
} from './index'
export async function getLocationWithSetting ( ) {
let res = await getSetting ( 'scope.userLocation' )
if ( res || res === undefined) {
return await getLocation ( )
} else {
let res1 = await openSetting ( 'scope.userLocation' )
if ( res1) {
return await getLocation ( )
} else
$msg ( "为了不影响您的使用,请授权定位" )
}
}
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] )
}
} )
} )
}
function getLocation ( ) {
return new Promise ( ( resolve) => {
wx. getLocation ( {
success ( {
longitude: lng,
latitude: lat
} ) {
resolve ( {
lng,
lat
} ) ;
} ,
fail: ( ) => $msg ( "为了不影响您的使用,请授权定位" )
} )
} )
}