慢吞云雾缓吐愁 发表于 2024-6-20 13:55:20

【uni-app】申请高德地图key,封装map.js,实现H5、iOS、Android通过getloc

map组件底子使用

<template>
<view class="contact">
    <image class="img" :src="formData.headImg"></image>
    <view class="info">
      <view @click="callPhone">联系电话:{{formData.phone}} ( 点击拨打 )</view>
      <view>地址:{{formData.addr}}</view>
    </view>
    <map class="map" v-if="showMap" :longitude="longitude" :scale="scale" :latitude="latitude" :markers="markers"></map>
</view>
</template>

<script>
export default {
    data() {
      return {
      showMap: false,
      formData:{
          headImg:'http://www.itcast.cn/2018czydz/images/gywmban.jpg',
          phone: '(0571)28828888',
          addr:'浙江省杭州市滨江区江南大道3588号'
      },
      longitude: 120.172341,
      latitude: 30.19159,
      scale: 13, // 缩放级别,取值范围为3-20, 默认16
      markers:[ // 标记点用于在地图上显示标记的位置,支持多个
          {
            longitude: 120.172341,
            latitude: 30.19159,
            iconPath: '../../static/logo.png',
            width: 20,
            height: 20,
            title:'ohh',// 点击时显示,callout存在时将被忽略
            label:{
                content:'呀哈哈'
            },
            callout:{
                content:`kkkk\r\nphds`
            }
          }
      ]
      }
    },
    mounted() {
      this.showMap = true;
    },
    methods: {
      phone() {
      uni.makePhoneCall({
          phoneNumber: this.formData.phone
      })
      }
    }
}
</script>

<style lang="scss">
.contact{
    .img{
      width: 750rpx;
      height: 320rpx;
    }
    .info{
      padding: 10rpx 20rpx;
      font-size: 30rpx;
      view{
            line-height: 80rpx;
            border-bottom: 1px solid #eee;
      }
    }
    .map{
      width: 750rpx;
      height: 750rpx;
    }
}
</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、创建应用:输入名称,选择应用类型https://img-blog.csdnimg.cn/direct/d7252acf4aa040b1a25a6ac18e843c73.png
https://img-blog.csdnimg.cn/direct/f19fe31c7a4e4cc6b0fd14ac0c659e95.png
3、应用右侧,点击添加key,添加h5 web端(JS API),h5需申请这个key,否则活报key无效或不匹配
https://img-blog.csdnimg.cn/direct/0a615f18e6014e6e8ced371de8d2c873.png
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,即可使用高德地图
https://img-blog.csdnimg.cn/direct/93691e2e3f5b4f44812f077441ab040b.png
https://img-blog.csdnimg.cn/direct/d33cb0878e2f47889ea62ad49a468565.png
https://img-blog.csdnimg.cn/direct/12de65cb194444c595ea1aa5121fba31.png
此时使用api获取当前定位,使用Google浏览器访问时,并不会触发获取当前位置api,而H5 端获取定位信息,要求部署在 https 服务上,检察配置是已经使用https协议
缘故原由是:国内使用Google浏览器访问极有可能被墙,以是可以使用其他浏览器进行测试或者科学上网。
接口文档:https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
https://img-blog.csdnimg.cn/direct/53379e440b46488fbd383a1596151f8c.png
配置使用https协议
https://img-blog.csdnimg.cn/direct/9ca2db5e8092421f9f4cfc7f90964190.png
通过uni.getLocation获取当前定位信息时,成功回调函数中会返回当前经纬度等信息,如果想获取当前省市区信息,可以设置参数 geocode 为 true,但该属性仅APP端支持,H5则需要再通过第三方(高德)逆地理编码分析出地址信息
逆地理编码需要web服务的key作为参数,以是需要再申请web服务的key
https://img-blog.csdnimg.cn/direct/7e8c37a92ef040cab08df4291b9626e9.png
// 转地址
turnAdrr(longs, lat) {
// 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
let _key = '22865bd225e8ce6a8dc04780e9d650c1';//高德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)
      const resData = res.data
      this.formData.addr = resData.regeocode.formatted_address
      this.latitude = lat
      this.longitude = longs
      this.markers.latitude = lat
      this.markers.longitude = longs
      this.showMap = true;
    },
    fail: r => {
      console.log(r);
    }
});
},
以上通过逆地理编码就可以得到当前定位的地理信息
https://img-blog.csdnimg.cn/direct/ec3db1492e424621bc137ad58e3ba31d.png
此时动态获取到当前定位信息,就可以把数据动态绑定到map组件中
到此H5使用第三方地图已完成。
2、申请微信小程序 key

1、申请微信小程序key
https://img-blog.csdnimg.cn/direct/6bf63492e79b4494afa9d2717504443f.png
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

https://img-blog.csdnimg.cn/direct/2f3e9665a86e4cd8bafa88a9e86e82ac.png
检察/设置Android包名

https://img-blog.csdnimg.cn/direct/6b1f452fe56d429799b29e7a222b3eb1.png
https://img-blog.csdnimg.cn/direct/7a0ff5fbe7b444e8adac60ac5e1d143a.png
2、获得SHA1安全码和包名之后,高德开放平台,添加Android key,并输入SHA1 和包名,点击确认即可天生key。
https://img-blog.csdnimg.cn/direct/62d4e32d2e51479ca43d8aa0dd022d32.png
3、复制Android key 添加到地图配置中。如果不打算申请ios,任意填一个或者都填Android的key。
https://img-blog.csdnimg.cn/direct/948bd368ac3f4eb69c2b58be1e40d234.png
https://img-blog.csdnimg.cn/direct/3ab622ca2fc340e4a7aae585761fd733.png
4、申请ios key

ios 申请相对有点贫苦,主要是需要登录apple 开发者平台https://developer.apple.com/注册开发者账号,然后申请ios正式,天生bundle id。
详细申请可以参考:http://news.558idc.com/288029.html
这里仅为了测试,就填了dcound提供的bundle id: io.dclound.HBuilder
https://img-blog.csdnimg.cn/direct/094d4bcc78ae4e3e8f9148afa610b9b5.png
点击提交,天生ios平台key,复制 key 添加到地图配置中
https://img-blog.csdnimg.cn/direct/fb46c2303d3f4044b7c6c42fef64a683.png
2、封装map

1、lib/map.js

以上各平台key申请完成之后,新建lib/map.js进行封装
//h5 要调用的js文件
// #ifdef H5
import amap from '@/utils/map-h5.js';
// #endif
//微信小程序要调用的js文件
// #ifdef MP
import amap from '@/utils/map-wx.js';
// #endif
//获取位置信息
const getlocation = (opt) => {
return new Promise((resolve, reject) => {
    //h5开始
    // #ifdef H5
    AMap.plugin('AMap.Geolocation', function() {
      uni.showLoading({
      title: '系统正在定位'
      });
      var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, //是否使用高精度定位,默认:true
      timeout: 10000, //超过10秒后停止定位,默认:5s
      buttonPosition: 'RB', //定位按钮的停靠位置
      buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
      zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
      });
      // console.log(geolocation,'geolocation')
      geolocation.getCurrentPosition(function(status, result) {
      console.log(status,'status')
      if (status == 'complete') {
          //这个地方的result,可能会出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
          //可能是密匙申请错了,重新申请密匙,生成maps.js文件。
          // console.log(result)
          uni.hideLoading();
          resolve(result)
      } else {
          uni.hideLoading();
          uni.showToast({
            title: '定位失败',
          });
          reject(result)
      }
      });
    });
    // #endif
    //h5结束
   
    //app开始
    // #ifdef APP-PLUS
    uni.showLoading({
      title: '获取信息中'
    });
    uni.getLocation({
      // map组件默认为国测局坐标gcj02,调用 uni.getLocation返回结果传递给组件时,需指定 type 为 gcj02
      type: 'gcj02',
      geocode: true,
      success: function(data) {
      resolve(data)
      },
      fail: function(err) {
      reject(err)
      },
      complete() {
      uni.hideLoading();
      }
    })
    // #endif
    //app结束
   
    ///小程序开始
    // #ifdef MP
    var amapPlugin = new amap.AMapWX({
      key: 'e7bdd77a10ffca3092c48032d1f74ace'//此处为高德平台申请的微信小程序的key
    });
    uni.showLoading({
      title: '获取信息中'
    });
    amapPlugin.getRegeo({
      success: function(data) {
      resolve(data)
      },
      fail: function(err) {
      reject(err)
      },
      complete: function() {
      uni.hideLoading();
      }
    });
    // #endif
    //小程序结束
})
};
export default {
getlocation: getlocation
}
2、main.js中全局引用:

import map from 'common/map.js'
Vue.prototype.$map = map;
3、使用

<template>
<view class="contact">
    <image class="img" :src="formData.headImg"></image>
    <view class="info">
      <view @click="callPhone">联系电话:{{formData.phone}} ( 点击拨打 )</view>
      <view>地址:{{formData.addr}}</view>
    </view>
    <map class="map" v-if="showMap" :longitude="longitude" :scale="scale" :latitude="latitude" :markers="markers"></map>
</view>
</template>
<script>
export default {
    data() {
      return {
      showMap:false,
      formData:{
          headImg:'http://www.itcast.cn/2018czydz/images/gywmban.jpg',
          phone: '(0571)28828888',
          addr:''
      },
      longitude: null,
      latitude: null,
      scale: 13, // 缩放级别,取值范围为3-20, 默认16
      markers:[ // 标记点用于在地图上显示标记的位置,支持多个
          {
            longitude: null,
            latitude: null,
            iconPath: '../../static/logo.png',
            width: 20,
            height: 20,
            title:'ohh',// 点击时显示,callout存在时将被忽略
            label:{
            content:'呀哈哈'
            },
            callout:{
            content:`kkkk\r\nphds`
            }
          }
      ]
      }
    },
    created() {
      this.init();
    },
    methods: {
      init(){
      this.$map.getlocation().then(res => {
          console.log(res)
          // #ifdef APP-PLUS
          this.formData.addr = res.address.province+res.address.city+res.address.district+res.address.street+res.address.streetNum+res.address.poiName;
          this.latitude = res.latitude
          this.longitude = res.longitude
          this.markers.latitude = res.latitude
          this.markers.longitude = res.longitude
          this.showMap = true;
          // #endif
          // #ifdef H5
          this.turnAdrr(res.longitude,res.latitude)
          // #endif
      }).catch(err => {
          console.log(err)
      })
      },
      // 转地址
      turnAdrr(longs, lat) {
      // 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
      let _key = '22865bd225e8ce6a8dc04780e9d650c1';//高德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)
            const resData = res.data
            this.formData.addr = resData.regeocode.formatted_address
            this.latitude = lat
            this.longitude = longs
            this.markers.latitude = lat
            this.markers.longitude = longs
            this.showMap = true;
          },
          fail: r => {
            console.log(r);
          }
      });
      },
      callPhone() {
      uni.makePhoneCall({
          phoneNumber: this.formData.phone
      })
      }
    }
}
</script>

<style lang="scss">
.contact{
.img{
    width: 750rpx;
    height: 320rpx;
}
.info{
    padding: 10rpx 20rpx;
    font-size: 30rpx;
    view{
      line-height: 80rpx;
      border-bottom: 1px solid #eee;
    }
}

.map{
    width: 750rpx;
    height: 750rpx;
}
}
</style>
注意:H5需要开启使用https协议,调试时不要使用:Chrome、火狐、安卓原生WebView等,会报错:Get geolocation timeout.Get ipLocation failed.
报错是定位超时,由于JSAPI 使用的是浏览器提供的定位服务,以是定位的准确度和成功率都会对浏览器有很大的依赖。由于Chrome在国内没有提供服务,因此使用Chrome定位服务的浏览器,比如:Chrome、火狐、安卓原生WebView等情况的原生定位通常都会定位失败;
建议更换浏览器测试,推荐使用Edge 浏览器,或者翻墙。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【uni-app】申请高德地图key,封装map.js,实现H5、iOS、Android通过getloc