1、第一步申请高德API的key,申请类型为【web端】与【web服务】
(1)【web端】主要是获取定位;
(2)【web服务】主要是uniapp H5端不能直接获取 地址信息(仅APP端支持),须先通过uni.getLocation获取经纬度,再通过第三方(高德)逆地理编码(高德逆地理编码)解析出地址信息
2、在H5 端使用地图和定位相关,需要在 manifest.json 内web配置腾讯或谷歌等三方地图服务商申请的秘钥(key),高德地图(web端key)需要额外配置 securityJsCode 或 serviceHost。配置了地图的key才能在H5中正常使用地图,否则会报 Map key is not configures。
遇到的坑:
1、H5 端获取定位信息,需要部署在 https 服务上,本地预览(localhost)仍然可以使用 http 协议。
2、用浏览器测试,需要打开浏览器的定位服务(本人用的是火狐);谷歌浏览器可能会获取不到任何信息,因为谷歌浏览器位置信息是连接谷歌服务器获取的,国内用户可能获取位置信息失败3、需要配置安全策略(nginx配置)
①查看配置文件路径;执行命令 nginx -t,已安装nginx话会返回nginx安装(/etc/nginx/nginx.conf )路径。
②修改nginx.conf文件;cd /etc/nginx打开nginx.conf找到add_header Content-Security-Policy添加第三方域名{*.amap.com(高德),*.qq.com(腾讯)} 例:
location / { root /项目路径; try_files $uri $uri/ /index.html $uri/ =404; index index.html index.htm; add_header X-Content-Type-Options 'nosniff';#禁止嗅探文件类型 add_header Content-Security-Policy "script-src 'self' *.amap.com *.qq.com 'unsafe-inline' 'unsafe-eval' blob: data: ;";#只允许同源下的js }
3、H5代码
//获取经纬度
getLocation() {
uni.getLocation({
type: 'gcj02', //返回可以用于uni.openLocation的经纬度
success: (res) => {
const longs = res.longitude.toString();
const lat = res.latitude.toString();
if (longs !== '' && lat !== '') {
this.turnAdrr(longs, lat)//经纬度转地区名
}
}
});
},
// 转地址
turnAdrr(longs, lat) {
// 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
let _key = '高德里你注册的key';//高德API key类型:web服务
uni.request({
method: 'GET',
url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
data: {
key: _key,
location: `${longs},${lat}`,
output: 'JSON'
},
success: async (res) => {
console.log(res.data.regeocode.formatted_address);
//用户所在的地理位置信息
},
fail: r => {
console.log(r);
}
});
},
APP代码
1、配置密钥
2、直接调用uni.getLocation()拿到用户的所在位置,不需要进行解析,可以直接拿到
uni.getLocation({
type: 'gcj02', //app直接获取地理位置信息要使用gcj02
geocode:true , //必须要将geocode配置为true
isHighAccuracy: true,
success(res) {
console.log(res.address)
},
fail(err){
console.log(err)
}
})