首先需要申请高德账号并把开发程序给绑定,这里直接跳过了
高德地图.png
然后在manifest.json中进行配置,这里的key都是图1中配置得到的key
高德地图2.png
首先先检查手机是否打开了定位权限,如果没有就弹框引导用户打开手机权限
export const openPosition = ()=>{
let system = uni.getSystemInfoSync()
if(system.platform === 'android'){//判断平台
var context = plus.android.importClass("android.content.Context")
var locationManager = plus.android.importClass("android.location.LocationManager")
var main = plus.android.runtimeMainActivity()
var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
console.log('GPS',mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER))
if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
uni.showModal({
title:'提示',
content:'请打开定位服务功能',
showCancel:false,
success() {
if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
let main = plus.android.runtimeMainActivity();
let Intent = plus.android.importClass("android.content.Intent");
let mIntent = new Intent('android.settings.ACTION_SETTINGS');
main.startActivity(mIntent);//打开系统设置GPS服务页面
}else{
uni.showToast({
title:'定位功能已启动',
duration:2000
})
}
}
})
}
}
}
先通过uniapp的api获取当前的地理位置坐标,然后通过高德api进行解析,获取地理位置数据
getCurLocation(){
uni.getLocation({
geocode:true,
type: 'gcj02',
success:async (res)=>{
let { pois } = await posToCity(
{
latitude: res.latitude,
longitude: res.longitude,
},
1
);
this.address = pois[0].title
this.latitude = res.latitude
this.longitude = res.longitude
uni.setStorageSync('latitude',res.latitude)
uni.setStorageSync('longitude',res.longitude)
this.curAddress = store.state.address.curPickAddress.title
}
})
}
// 高德坐标解析
export const posToCity = async (location, extensions = 0) => new Promise((resolve, reject) => {
uni.request({
url: `https://restapi.amap.com/v3/geocode/regeo`,
method: 'GET',
data: {
key: gdMapKey,
location: `${location.longitude},${location.latitude}`,
extensions: extensions ? 'all' : 'base'
},
success: ({data}) => {
const {status, info, regeocode} = data
if (status === '1') {
// console.log(regeocode)
if ('pois' in regeocode) {
regeocode.pois = regeocode.pois.filter(item => typeof item.address === 'string' && typeof item.location === 'string').map(item => ({
id: item.id,
title: item.name,
address: item.address,
location: {
lat: item.location.split(',')[1],
lng: item.location.split(',')[0]
}
}))
}
resolve(regeocode)
} else {
reject(info)
}
},
fail: err => {
reject(err)
}
})
})
最后拿到数据进行渲染,得到成果图
高德地图3.jpg