【uni-app】申请高德地图key,封装map.js,实现H5、iOS、Android通过getlocation获取地图定位信息(摘)
一、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
申请H5 key
①登录高德开放平台(https://console.amap.com/dev),没有账号需要先注册开发者账号
②、创建应用:输入名称,选择应用类型

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

④、获取key值后浏览器访问该链接,
记得替换key值: https://webapi.amap.com/maps?v=1.4.15&key=申请的key值,项目中创建map-h5.js, 将访问到的js复制并粘贴到map-h5.js,这里我存放的路径是utils/maps-h5.js
⑤、如果不做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

// 转地址 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[0].latitude = lat this.markers[0].longitude = longs this.showMap = true; }, fail: r => { console.log(r); } }); },

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

  2、下载小程序的js文件链接:https://lbs.amap.com/api/wx/download
  3、下载完后将amap-wx.js文件解压到项目即可(主要为了封装map全局调用)
申请android key
  1、申请Android证书
  在uni-app官方文档https://uniapp.dcloud.net.cn/左侧菜单,点击uniClound web端控制台https://unicloud.dcloud.net.cn/,登录开发者账号,然后点击账号管理,左侧菜单:应用管理-我的应用,    找到需要创建Android正式的项目
点击项目名称-Android云端正式,点击创建证书===》点击确定,等待几分钟,正式就创建好了。
查看证书详情,可以看到SHA1


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

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

申请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进行封装
//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[0].latitude = res.latitude this.markers[0].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[0].latitude = lat this.markers[0].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 浏览器,或者FQ。
原文地址:https://blog.csdn.net/ChenLingZhi1115/article/details/139446557
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号