uniapp定位描述
获取定位权限
在manifest.json文件中配置定位权限,确保应用有权访问设备位置信息。对于Android平台,需要添加以下权限配置:
"permission": [
"android.permission.ACCESS_COARSE_LOCATION",
"android.permission.ACCESS_FINE_LOCATION"
]
iOS平台需在manifest.json的ios节点下添加:
"permissions": {
"LOCATION_WHEN_IN_USE": "描述定位用途"
}
使用uni.getLocation API
通过uni.getLocation方法获取当前位置信息。示例代码展示基本调用方式:
uni.getLocation({
type: 'wgs84',
success: function(res) {
console.log('纬度:' + res.latitude);
console.log('经度:' + res.longitude);
},
fail: function(err) {
console.error('定位失败:', err);
}
});
参数type支持wgs84(GPS标准)和gcj02(国测局坐标)。
处理高精度定位需求
对于需要更高精度的场景,可设置isHighAccuracy和highAccuracyExpireTime参数:

uni.getLocation({
type: 'wgs84',
isHighAccuracy: true,
highAccuracyExpireTime: 5000,
success(res) {
// 高精度结果处理
}
});
实现持续定位监听
使用uni.onLocationChange监听位置变化,适合导航类应用:
const locationListener = uni.onLocationChange({
type: 'gcj02',
success: function(res) {
console.log('实时位置:', res);
}
});
// 需要停止时调用
locationListener.off();
地图组件集成
在页面中显示位置时,配合使用<map>组件:
<map
:latitude="latitude"
:longitude="longitude"
:markers="markers"
style="width:100%;height:300px">
</map>
JavaScript部分需设置对应数据:

data() {
return {
latitude: 39.908823,
longitude: 116.397470,
markers: [{
id: 1,
latitude: 39.908823,
longitude: 116.397470,
title: '当前位置'
}]
}
}
跨平台兼容处理
针对不同平台的特性差异进行适配:
- iOS需确保
NSLocationWhenInUseUsageDescription在原生配置中已设置 - Android6.0+需要动态申请权限,可使用
uni.authorize提前获取权限 - 微信小程序需在
app.json中声明permission字段
错误处理与降级方案
完善错误处理逻辑并提供备选方案:
uni.getLocation({
fail(err) {
if (err.errMsg.includes('auth deny')) {
uni.showModal({
title: '提示',
content: '请开启定位权限',
success(res) {
if (res.confirm) {
uni.openSetting();
}
}
});
} else {
// 使用IP定位等降级方案
}
}
});
坐标转换处理
不同地图服务商使用不同坐标系,必要时进行坐标转换:
// 示例:GCJ02转BD09(百度坐标)
function gcj02tobd09(lng, lat) {
const x_PI = 3.14159265358979324 * 3000.0 / 180.0;
const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
return {
lng: z * Math.cos(theta) + 0.0065,
lat: z * Math.sin(theta) + 0.006
};
}
性能优化建议
- 合理设置定位间隔时间,避免频繁调用消耗电量
- 考虑使用缓存机制存储最近一次定位结果
- 后台定位功能需按需使用,Android需单独配置后台定位权限
- 使用
uni.chooseLocation可调用系统地图选点功能减少开发量






