ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【uni-app】申请高德地图key,封装map.js,实现H5、iOS、Android通过getloc [打印本页]

作者: 慢吞云雾缓吐愁    时间: 2024-6-20 13:55
标题: 【uni-app】申请高德地图key,封装map.js,实现H5、iOS、Android通过getloc
map组件底子使用

  1. <template>
  2.   <view class="contact">
  3.     <image class="img" :src="formData.headImg"></image>
  4.     <view class="info">
  5.       <view @click="callPhone">联系电话:{{formData.phone}} ( 点击拨打 )</view>
  6.       <view>地址:{{formData.addr}}</view>
  7.     </view>
  8.     <map class="map" v-if="showMap" :longitude="longitude" :scale="scale" :latitude="latitude" :markers="markers"></map>
  9.   </view>
  10. </template>
  11. <script>
  12.   export default {
  13.     data() {
  14.       return {
  15.         showMap: false,
  16.         formData:{
  17.           headImg:'http://www.itcast.cn/2018czydz/images/gywmban.jpg',
  18.           phone: '(0571)28828888',
  19.           addr:'浙江省杭州市滨江区江南大道3588号'
  20.         },
  21.         longitude: 120.172341,
  22.         latitude: 30.19159,
  23.         scale: 13, // 缩放级别,取值范围为3-20, 默认16
  24.         markers:[ // 标记点用于在地图上显示标记的位置,支持多个
  25.           {
  26.             longitude: 120.172341,
  27.             latitude: 30.19159,
  28.             iconPath: '../../static/logo.png',
  29.             width: 20,
  30.             height: 20,
  31.             title:'ohh',// 点击时显示,callout存在时将被忽略
  32.             label:{
  33.                 content:'呀哈哈'
  34.             },
  35.             callout:{
  36.                 content:`kkkk\r\nphds`
  37.             }
  38.           }
  39.         ]
  40.       }
  41.     },
  42.     mounted() {
  43.       this.showMap = true;
  44.     },
  45.     methods: {
  46.       phone() {
  47.         uni.makePhoneCall({
  48.           phoneNumber: this.formData.phone
  49.         })
  50.       }
  51.     }
  52.   }
  53. </script>
  54. <style lang="scss">
  55. .contact{
  56.     .img{
  57.         width: 750rpx;
  58.         height: 320rpx;
  59.     }
  60.     .info{
  61.         padding: 10rpx 20rpx;
  62.         font-size: 30rpx;
  63.         view{
  64.             line-height: 80rpx;
  65.             border-bottom: 1px solid #eee;
  66.         }
  67.     }
  68.     .map{
  69.         width: 750rpx;
  70.         height: 750rpx;
  71.     }
  72. }
  73. </style>
复制代码
封装map.js,实现定位

1、使用第三方地图:高德,申请对应平台key

注:高德地图web js api:https://lbs.amap.com/api/javascript-api/guide/abc/prepare
1、申请H5 key

1、登录高德开放平台
(https://console.amap.com/dev),没有账号需要先注册开发者账号
2、创建应用:输入名称,选择应用类型


3、应用右侧,点击添加key,添加h5 web端(JS API),h5需申请这个key,否则活报key无效或不匹配

4、获取key值后浏览器访问该链接,
记得替换key值: https://webapi.amap.com/maps?v=1.4.15&key=申请的key值,项目中创建map-h5.js, 将访问到的js复制并粘贴到map-h5.js,这里我存放的路径是utils/maps-h5.js
5、如果不做map封装,可以不执行上一步,只需把申请到的web端的key和安全秘钥配置到项目标manifest.json,即可使用高德地图



此时使用api获取当前定位,使用Google浏览器访问时,并不会触发获取当前位置api,而H5 端获取定位信息,要求部署在 https 服务上,检察配置是已经使用https协议
缘故原由是:国内使用Google浏览器访问极有可能被墙,以是可以使用其他浏览器进行测试或者科学上网。

接口文档:https://uniapp.dcloud.net.cn/api/location/location.html#getlocation

配置使用https协议

通过uni.getLocation获取当前定位信息时,成功回调函数中会返回当前经纬度等信息,如果想获取当前省市区信息,可以设置参数 geocode 为 true,但该属性仅APP端支持,H5则需要再通过第三方(高德)逆地理编码分析出地址信息
逆地理编码需要web服务的key作为参数,以是需要再申请web服务的key


  1. // 转地址
  2. turnAdrr(longs, lat) {
  3.   // 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
  4.   let _key = '22865bd225e8ce6a8dc04780e9d650c1';//高德API key类型:web服务
  5.   uni.request({
  6.     method: 'GET',
  7.     url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
  8.     data: {
  9.       key: _key,
  10.       location: `${longs},${lat}`,
  11.       output: 'JSON'
  12.     },
  13.     success: async (res) => {
  14.       console.log(res)
  15.       const resData = res.data
  16.       this.formData.addr = resData.regeocode.formatted_address
  17.       this.latitude = lat
  18.       this.longitude = longs
  19.       this.markers[0].latitude = lat
  20.       this.markers[0].longitude = longs
  21.       this.showMap = true;
  22.     },
  23.     fail: r => {
  24.       console.log(r);
  25.     }
  26.   });
  27. },
复制代码
以上通过逆地理编码就可以得到当前定位的地理信息

此时动态获取到当前定位信息,就可以把数据动态绑定到map组件中
到此H5使用第三方地图已完成。
2、申请微信小程序 key

1、申请微信小程序key

2、下载小程序的js文件链接:https://lbs.amap.com/api/wx/download
3、下载完后将amap-wx.js文件解压到项目即可(主要为了封装map全局调用)
3、申请android key

1、申请Android证书
在uni-app官方文档https://uniapp.dcloud.net.cn/左侧菜单,点击uniClound web端控制台https://unicloud.dcloud.net.cn/,登录开发者账号,然后点击账号管理,左侧菜单:应用管理-我的应用,找到需要创建Android正式的项目
点击项目名称-Android云端正式,点击创建证书===》点击确定,等候几分钟,正式就创建好了。
检察证书详情,可以看到SHA1


检察/设置Android包名



2、获得SHA1安全码和包名之后,高德开放平台,添加Android key,并输入SHA1 和包名,点击确认即可天生key。

3、复制Android key 添加到地图配置中。如果不打算申请ios,任意填一个或者都填Android的key。


4、申请ios key

ios 申请相对有点贫苦,主要是需要登录apple 开发者平台https://developer.apple.com/注册开发者账号,然后申请ios正式,天生bundle id。
详细申请可以参考:http://news.558idc.com/288029.html
这里仅为了测试,就填了dcound提供的bundle id: io.dclound.HBuilder

点击提交,天生ios平台key,复制 key 添加到地图配置中

2、封装map

1、lib/map.js

以上各平台key申请完成之后,新建lib/map.js进行封装
  1. //h5 要调用的js文件
  2. // #ifdef H5
  3. import amap from '@/utils/map-h5.js';
  4. // #endif
  5. //微信小程序要调用的js文件
  6. // #ifdef MP  
  7. import amap from '@/utils/map-wx.js';
  8. // #endif
  9. //获取位置信息
  10. const getlocation = (opt) => {
  11.   return new Promise((resolve, reject) => {
  12.     //h5开始
  13.     // #ifdef H5
  14.     AMap.plugin('AMap.Geolocation', function() {
  15.       uni.showLoading({
  16.         title: '系统正在定位'
  17.       });
  18.       var geolocation = new AMap.Geolocation({
  19.         enableHighAccuracy: true, //是否使用高精度定位,默认:true
  20.         timeout: 10000, //超过10秒后停止定位,默认:5s
  21.         buttonPosition: 'RB', //定位按钮的停靠位置
  22.         buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
  23.         zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
  24.       });
  25.       // console.log(geolocation,'geolocation')
  26.       geolocation.getCurrentPosition(function(status, result) {
  27.         console.log(status,'status')
  28.         if (status == 'complete') {
  29.           //这个地方的result,可能会出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
  30.           //可能是密匙申请错了,重新申请密匙,生成maps.js文件。
  31.           // console.log(result)
  32.           uni.hideLoading();
  33.           resolve(result)
  34.         } else {
  35.           uni.hideLoading();
  36.           uni.showToast({
  37.             title: '定位失败',
  38.           });
  39.           reject(result)
  40.         }
  41.       });
  42.     });
  43.     // #endif
  44.     //h5结束
  45.    
  46.     //app开始
  47.     // #ifdef APP-PLUS
  48.     uni.showLoading({
  49.       title: '获取信息中'
  50.     });
  51.     uni.getLocation({
  52.       // map组件默认为国测局坐标gcj02,调用 uni.getLocation返回结果传递给组件时,需指定 type 为 gcj02
  53.       type: 'gcj02',
  54.       geocode: true,
  55.       success: function(data) {
  56.         resolve(data)
  57.       },
  58.       fail: function(err) {
  59.         reject(err)
  60.       },
  61.       complete() {
  62.         uni.hideLoading();
  63.       }
  64.     })
  65.     // #endif
  66.     //app结束
  67.    
  68.     ///小程序开始
  69.     // #ifdef MP
  70.     var amapPlugin = new amap.AMapWX({
  71.       key: 'e7bdd77a10ffca3092c48032d1f74ace'  //此处为高德平台申请的微信小程序的key
  72.     });
  73.     uni.showLoading({
  74.       title: '获取信息中'
  75.     });
  76.     amapPlugin.getRegeo({
  77.       success: function(data) {
  78.         resolve(data)
  79.       },
  80.       fail: function(err) {
  81.         reject(err)
  82.       },
  83.       complete: function() {
  84.         uni.hideLoading();
  85.       }
  86.     });
  87.     // #endif
  88.     //小程序结束
  89.   })
  90. };
  91. export default {
  92.   getlocation: getlocation
  93. }
复制代码
2、main.js中全局引用:

  1. import map from 'common/map.js'
  2. Vue.prototype.$map = map;
复制代码
3、使用

  1. <template>
  2.   <view class="contact">
  3.     <image class="img" :src="formData.headImg"></image>
  4.     <view class="info">
  5.       <view @click="callPhone">联系电话:{{formData.phone}} ( 点击拨打 )</view>
  6.       <view>地址:{{formData.addr}}</view>
  7.     </view>
  8.     <map class="map" v-if="showMap" :longitude="longitude" :scale="scale" :latitude="latitude" :markers="markers"></map>
  9.   </view>
  10. </template>
  11. <script>
  12.   export default {
  13.     data() {
  14.       return {
  15.         showMap:false,
  16.         formData:{
  17.           headImg:'http://www.itcast.cn/2018czydz/images/gywmban.jpg',
  18.           phone: '(0571)28828888',
  19.           addr:''
  20.         },
  21.         longitude: null,
  22.         latitude: null,
  23.         scale: 13, // 缩放级别,取值范围为3-20, 默认16
  24.         markers:[ // 标记点用于在地图上显示标记的位置,支持多个
  25.           {
  26.             longitude: null,
  27.             latitude: null,
  28.             iconPath: '../../static/logo.png',
  29.             width: 20,
  30.             height: 20,
  31.             title:'ohh',// 点击时显示,callout存在时将被忽略
  32.             label:{
  33.               content:'呀哈哈'
  34.             },
  35.             callout:{
  36.               content:`kkkk\r\nphds`
  37.             }
  38.           }
  39.         ]
  40.       }
  41.     },
  42.     created() {
  43.       this.init();
  44.     },
  45.     methods: {
  46.       init(){
  47.         this.$map.getlocation().then(res => {
  48.           console.log(res)
  49.           // #ifdef APP-PLUS
  50.           this.formData.addr = res.address.province+res.address.city+res.address.district+res.address.street+res.address.streetNum+res.address.poiName;
  51.           this.latitude = res.latitude
  52.           this.longitude = res.longitude
  53.           this.markers[0].latitude = res.latitude
  54.           this.markers[0].longitude = res.longitude
  55.           this.showMap = true;
  56.           // #endif
  57.           // #ifdef H5
  58.           this.turnAdrr(res.longitude,res.latitude)
  59.           // #endif
  60.         }).catch(err => {
  61.           console.log(err)
  62.         })
  63.       },
  64.       // 转地址
  65.       turnAdrr(longs, lat) {
  66.         // 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
  67.         let _key = '22865bd225e8ce6a8dc04780e9d650c1';//高德API key类型:web服务
  68.         uni.request({
  69.           method: 'GET',
  70.           url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
  71.           data: {
  72.             key: _key,
  73.             location: `${longs},${lat}`,
  74.             output: 'JSON'
  75.           },
  76.           success: async (res) => {
  77.             console.log(res)
  78.             const resData = res.data
  79.             this.formData.addr = resData.regeocode.formatted_address
  80.             this.latitude = lat
  81.             this.longitude = longs
  82.             this.markers[0].latitude = lat
  83.             this.markers[0].longitude = longs
  84.             this.showMap = true;
  85.           },
  86.           fail: r => {
  87.             console.log(r);
  88.           }
  89.         });
  90.       },
  91.       callPhone() {
  92.         uni.makePhoneCall({
  93.           phoneNumber: this.formData.phone
  94.         })
  95.       }
  96.     }
  97.   }
  98. </script>
  99. <style lang="scss">
  100. .contact{
  101.   .img{
  102.     width: 750rpx;
  103.     height: 320rpx;
  104.   }
  105.   .info{
  106.     padding: 10rpx 20rpx;
  107.     font-size: 30rpx;
  108.     view{
  109.       line-height: 80rpx;
  110.       border-bottom: 1px solid #eee;
  111.     }
  112.   }
  113.   
  114.   .map{
  115.     width: 750rpx;
  116.     height: 750rpx;
  117.   }
  118. }
  119. </style>
复制代码
注意:H5需要开启使用https协议,调试时不要使用:Chrome、火狐、安卓原生WebView等,会报错:Get geolocation timeout.Get ipLocation failed.
报错是定位超时,由于JSAPI 使用的是浏览器提供的定位服务,以是定位的准确度和成功率都会对浏览器有很大的依赖。由于Chrome在国内没有提供服务,因此使用Chrome定位服务的浏览器,比如:Chrome、火狐、安卓原生WebView等情况的原生定位通常都会定位失败;
建议更换浏览器测试,推荐使用Edge 浏览器,或者翻墙。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4