/**在app中获取定位*/
import permision from "@/utils/permission.js";
import userAuthorize from "@/utils/authorize.js"
const authKey = {
text: '未开启位置权限',
ios: 'location',
Android: 'android.permission.ACCESS_FINE_LOCATION'
}
function getLocationClass(){
return new Promise((resolve, reject) => {
//api获取经纬度
uni.getLocation({
type: 'wgs84',
isHighAccuracy: true,
success: (res) => {
//获取用户坐标
let latitude = res.latitude;
let longitude = res.longitude;
resolve({latitude, longitude});
},fail: (e) => {
userAuthorize(authKey, state => {
if(!state) return
uni.showModal({
title: '系统提示',
content: '定位失败,请检查网络或系统定位',
cancelText: '手动定位',
confirmText: '重新定位',
success: function (res) {
if (res.confirm) {
//重新调用定位方法
getLocationClass();
} else if (res.cancel) {
resolve(false);
}
}
});
})
}
})
})
}
/**判断当前手机是否开启了定位服务*/
function getLocation(){
return new Promise(async (resolve, reject) => {
if(permision.checkSystemEnableLocation()){
//当前已经开启了定位服务,那么可以直接获取当前经纬度
try{
const data = await getLocationClass();
resolve(data)
}catch(e){
reject(e)
}
}else{
uni.showModal({
title: '系统提示',
content: '是否去开启定位',
success: function (res) {
if(uni.getSystemInfoSync().platform == 'ios'){ //ios系统的定位服务设置调起
let UIApplication = plus.ios.import("UIApplication");
let application2 = UIApplication.sharedApplication();
let NSURL2 = plus.ios.import("NSURL");
let setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
application2.openURL(setting2);
plus.ios.deleteObject(setting2);
plus.ios.deleteObject(NSURL2);
plus.ios.deleteObject(application2);
}else{ //安卓系统的定位服务设置调起
let Intent = plus.android.importClass('android.content.Intent');
let Settings = plus.android.importClass('android.provider.Settings');
let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
let main = plus.android.runtimeMainActivity();
main.startActivity(intent); // 打开系统设置GPS服务页面
}
}
})
}
})
}
export default getLocation
authorize.js和permision.js 看另外一篇文章uniapp授权_HSL-的博客-CSDN博客
wgs84获取到的经纬度偏差比较大,建议用gcj02 并且在app模块配置高德sdk
引入使用:
<template>
<view>
<u-button type="primary" text="定位" @click="hanldeLocation"></u-button>
<view>{{ address }}</view>
</view>
</template>
<script>
import getLocationAppApi from '@/utils/location.js';
export default {
data() {
return {
address: ''
}
},
methods: {
getloadCity(latitude, longitude) {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '获取中'
})
// 随便拿了一个腾讯地图的api获取地址,key换成自己的
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude+','+longitude+'&key=xxxxxxxxx',
success: function(res) {
uni.hideLoading()
resolve(res);
},fail: function(err) {
uni.hideLoading()
reject(err)
}
})
})
},
async hanldeLocation() {
try{
// 授权获取经纬度
const {latitude, longitude} = await getLocationAppApi();
// 获取地址
const res = await this.getloadCity(latitude, longitude);
this.address = res.data.result.address
}catch(e){
console.log(e);
}
}
}
}
</script>