uniapp APP&H5端获取地理位置信息(百度地图&高德地图) |
您所在的位置:网站首页 › 定位不行 › uniapp APP&H5端获取地理位置信息(百度地图&高德地图) |
APP&H5端获取地理位置信息
一、app端
1.在需要使用的页面中 onShow(){ //#ifdef APP-PLUS // 获取定位信息 this.getLocations(); //#endif }, methods:{ //获取定位信息 getPosition(){ const that = this; uni.getLocation({ type: 'wgs84', geocode:true,//设置该参数为true可直接获取经纬度及城市信息 success: function (res) { console.log('获取定位信息',res); that.latitude = res.latitude; that.longitude = res.longitude; that.area = res.address.city; }, fail: function (err) { console.log("获取定位失败",err); uni.showToast({ title: '获取地址失败,将导致部分功能不可用', icon:'none' }); } }); } }2.在高德地图或百度地图开放平台申请key 高德地图开放平台 https://console.amap.com/dev/key/app 百度地图开放平台 https://lbsyun.baidu.com/ 注意:申请key时,SHA1码为打包证书的SHA1码,packageName为打包时的包名,一定要与打包时的参数一致 3.在manifest.json --> App模块配置中, 勾选maps地图选项,选用百度地图或者高德地图均可,填写相应平台申请的key值 1.申请key, H5端使用的key值与移动端不同,需在申请时选择 web服务 2.在需要使用的页面中 onShow(){ // 获取定位信息 this.getLocations(); }, methods:{ //获取定位信息 getPosition(){ const that = this; uni.getLocation({ type: 'wgs84', success: function (lb) { console.log("位置信息",lb); console.log('当前位置的经度:' + lb.longitude); console.log('当前位置的纬度:' + lb.latitude); that.latitude = lb.latitude; that.longitude = lb.longitude; console.log(lb.longitude,lb.latitude); let key = 'ba463886fda3c3bd3b461cd0166e4249';//高德地图key uni.request({ // 高德 url:'https://restapi.amap.com/v3/geocode/regeo?output=json&location='+lb.longitude+ ',' + lb.latitude + '&key='+key +'&radius=1000&extensions=all', data: {}, header: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin':'*' }, success: function (res) { console.log('高德地图API接口返回信息',res) that.area = res.data.regeocode.addressComponent.city; }, }) }, }) } } (2)使用 百度地图 API H5端使用百度地图存在跨域问题,这里使用jsonp解决跨域问题ps: H5端使用的key值与移动端不同,需在申请时选择 web服务 1.安装 vue-jsonp npm i --save vue-jsonp2.在 main.js 中全局注册 // 解决百度地图跨域问题 import {VueJsonp} from 'vue-jsonp' Vue.use(VueJsonp)3.在需要使用的页面中 onShow(){ //#ifdef H5 // 获取定位信息 this.getLocations(); //#endif }, methods:{ //获取定位信息 getPosition(){ const that = this; uni.getLocation({ type: 'wgs84', success: function (lb) { console.log("位置信息",lb); console.log('当前位置的经度:' + lb.longitude); console.log('当前位置的纬度:' + lb.latitude); that.latitude = lb.latitude; that.longitude = lb.longitude; console.log(lb.longitude,lb.latitude); //使用jsonp解决百度地图的跨域问题 that.$jsonp( 'http://api.map.baidu.com/reverse_geocoding/v3/ak=NEXIhGPsRgKDcGa1Ox2OWj61ifdFhnCy&output=json&coordtype=wgs84ll&location='+lb.latitude+ ',' + lb.longitude, ).then(res => { console.log(res,'百度') that.area = res.result.addressComponent.city; console.log("that.area",that.area); uni.setStorageSync('area',that.area); }) }, }) } }4.若无法获取返回值,需在manifest.json --> h5配置中, 定位和地图选项,并填写在腾讯地图应用中申请的key 腾讯地图 https://lbs.qq.com/dev/console/application/mine |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |