900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 微信公众号开发(5)-调用jssdk获取地理位置经纬度及百度api获得城市

微信公众号开发(5)-调用jssdk获取地理位置经纬度及百度api获得城市

时间:2023-04-10 16:30:35

相关推荐

微信公众号开发(5)-调用jssdk获取地理位置经纬度及百度api获得城市

调用微信的jssdk需要先绑定js安全域名,这个在微信公众号后台自己设置就可以了。还需要引入js文件,但由于我使用了vux,它里面的WeChatPlugin这个插件可以直接用commonJS方式引用,不需要再引用jsw文件,所以我直接在main.js中引入了插件,代码如下

import { WechatPlugin } from 'vux'Vue.use(WechatPlugin)console.log(Vue.wechat) // 可以直接访问 wx 对象。

使用jssdk还需要注入配置信息,可以通过config接口注入权限验证配置,config获取配置信息方法如下:

wxConfig(WxUrl,apiList) {//微信验证信息来调用jssdkconst url = $config.baseURL+`api/public/weixin/getParams?signUrl=`+ WxUrl;$axios.get(url,{}).then(res => {const data = res.data.result;WechatPlugin.$wechat.config({debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId: data.appId || '', // 必填,企业号的唯一标识,此处填写企业号corpidtimestamp: data.timestamp || '', // 必填,生成签名的时间戳nonceStr: data.nonceStr || '', // 必填,生成签名的随机串signature: data.signature || '',// 必填,签名jsApiList: apiList || [] // 必填,需要使用的JS接口列表});}).catch(err => {// 所有error情况统一在此处理,包括返回状态码为200,但response.data.success为false的情况// console.log(err);});},

获取到配置信息之后就可以调用相应的api来获得信息了,我在页面挂载的时候注入配置信息,并且调用获取经纬度的接口:

WX_CONFIGS.wxConfig(encodeURIComponent(window.location.href.split('#')[0]), ['getLocation']);//注册微信获取位置接口this.$wechat.ready(() => {console.log('这里是config success,说明验证成功');this.getCurrentLocation();//通过经纬度获得位置});this.$wechat.error((err) => {// console.log(err);});

获取经纬度的方法:

getCurrentLocation(){//微信api获取当前经纬度let that = this;that.$wechat.getLocation({type: 'wgs84', // gps坐标 百度地图api用的百度坐标可能有偏差success: function (res) {let latitude = res.latitude;let longitude = res.longitude;let params = {"Longitude": longitude,"Latitude": latitude,};that.getCurrentCity(params.Longitude, params.Latitude);//根据经纬度获取城市}});},

获得经纬度之后我们可以用百度地图的api获得省市行政区和街道等信息,获取的方法如下:

getCurrentCity(longitude, latitude){//获取当前城市,行政区 // 百度地图API功能let address = "";let point = new BMap.Point(longitude, latitude);let gc = new BMap.Geocoder();gc.getLocation(point, function (rs) {let addComp = rs.addressComponents;//详细地址为省,市,行政区,街道,街道地址address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;window.localStorage.city = addComp.city;//当前城市window.localStorage.district = addComp.district;});},

注意百度地图在使用的时候需要去官网注册并且获得一个key,才能正常调用,不然会报错。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。