需要结合百度地图的 API, 请先完成这篇文章的流程: 使用百度地图将经纬度转换成具体位置
以 vuejs 为例
- beforeMount () {
- var that = this;
this.city = 正在定位城市...;
- this.wxapi.getWxConfig({url: window.location.href.split(#)[0]
- }).then(_ => {
- if (+(_.returnCode) == 0) {
- // 初始化微信配置
- wx.config(_.data);
- // 微信初始化事件
- wx.ready(function(){
- // 调用微信定位接口
- wx.getLocation({
- type: wgs84, // 默认为 wgs84 的 gps 坐标, 如果要返回直接给 openLocation 用的火星坐标, 可传入 gcj02
- success: function (res) {
- var latitude = res.latitude; // 纬度, 浮点数, 范围为 90 ~ -90
- var longitude = res.longitude; // 经度, 浮点数, 范围为 180 ~ -180
- if (latitude && longitude) {
- window.getlocation = function (data) {
- Loader.hideAll();
- if (data.status == 0) {
- var city = data.result.addressComponent.city
- Toast("定位到当前城市为:" + city);
- that.city = city
- this.$store.state.city = city
- } else {
- Toast(地址解析失败, 请手动选择城市)
- that.$router.push(/cityselect)
- }
- }
- Loader.show(正在定位...);
- var o = document.createElement(script);
- o.src = `http://api.map.baidu.com/geocoder/v2/?callback=getlocation&location=${latitude},${longitude}&output=json&pois=1&ak=PaY0aQpuk5ypaxL1bGH4y65nbitEd0u3`;
- document.documentElement.childNodes[0].appendChild(o);
- } else {
- Toast(微信定位失败, 请手动选择城市)
- that.$router.push(/cityselect)
- }
- }
- });
- });
- // config 信息验证失败会执行 error 函数, 如签名过期导致验证失败, 具体错误信息可以打开 config 的 debug 模式查看, 也可以在返回的 res 参数中查看, 对于 SPA 可以在这里更新签名
- wx.error(function(res){
- that.city = "定位失败, 请手动选择城市";
- Toasrt(微信接口调用失败, 请手动选择城市)
- that.$router.push(/cityselect)
- });
- } else {
- Toast("获取微信配置失败" + _.msg);
- that.city = "定位失败, 请手动选择城市";
- that.$router.push(/cityselect)
- }
- })
- }
来源: http://www.bubuko.com/infodetail-2541151.html