编程技术 2023-03-08 10:40:46 评论:0    浏览:46    

微信小程序提供的只有获取到经纬度的接口没有直接获取城市的接口

方案一

小程序调用wx.getLocation()获取经纬度,然后调用高德的接口获取当前城市,代码如下:

// findLocation(){// uni.showLoading({title:"定位中....",mask:true})// uni.getLocation({// type: 'gcj02',// success: async res => {// let { longitude, latitude } = res;// let result = await wxGetAddress({ longitude, latitude });// let province = result.regeocodeData.addressComponent.province// let cityName = result.regeocodeData.addressComponent.city// this.locationCity = cityName// let lifeData = uni.getStorageSync('lifeData');// let vuex_city = lifeData.vuex_city// if(!vuex_city){// this.$u.vuex('vuex_city', cityName);// }// uni.hideLoading();// }// });// }// import amapFile from '../../libs/amap-wx.130.js'// const myAmapFun = new amapFile.AMapWX({// // 申请的高德key值// key: '4ef3b3b42d8bb823529908dc93414127'// }); //创建一个实例化对象 // export default function wxGetAddress({longitude,latitude}) {// //根据传递进来经纬度进行反解析,调用的是高德给的方法// return new Promise((resolve, reject) => {// myAmapFun.getRegeo({// location: `${longitude},${latitude}`,// success: (res) => {// resolve(res[0])// },// fail: (err) => {// resolve(null)// }// })// })// }方案二

微信调用wx.getLocation()获取经纬度,审核过于麻烦,审核了很多次都不给通过,果断放弃。因此开源字节的租房小程序使用ip进行城市定位。代码如下:

findLocation(){let that = thisuni.showLoading({title:"定位中....",mask:true})this.$u.get("/api/profile/getRealCity").then(obj => {let cityName = obj.msgif(cityName){this.locationCity = cityNamelet lifeData = uni.getStorageSync('lifeData');let vuex_city = lifeData.vuex_cityif(!vuex_city){this.$u.vuex('vuex_city', cityName);}uni.hideLoading();}else{uni.request({// url:'https://pv.sohu.com/cityjson?ie=utf-8',url:'https://tianqiapi.com/ip?version=v9&appid=23035354&appsecret=8YvlPNrz',success(resp) {let ip = resp.data.ipthat.$u.get("/api/profile/getRealCityByIP?ip=" ip).then(obj => {let cityName = obj.msgif(cityName){that.locationCity = cityNamelet lifeData = uni.getStorageSync('lifeData');let vuex_city = lifeData.vuex_cityif(!vuex_city){that.$u.vuex('vuex_city', cityName);}uni.hideLoading();}else{that.$mytip.toast('定位失败')}uni.hideLoading();});}})}});}

通过方案二即可满足定位需求,需注意以下几个点:

1、我们的nginx被微信代理后无法获取到真实ip,因此使用第三方接口获取ip

2、微信小程序只能使用备案的域名,我们需要将获取ip的接口添加到白名单中

3、获取到ip后,再请求后台地址得到城市信息

以上代码在我们的开源项目中都能获取到,感兴趣的小伙伴可以前往我们的开源仓库

如若转载,请注明出处:开源字节 https://sourcebyte.cn/article/207.html

以上内容为【租房小程序自动定位城市(ip精准定位代码)】的相关内容。

 
免责声明:

本文内容来自用户上传并发布或网络新闻客户端自媒体,本站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请联系删除。

 
0相关评论
打赏