小程序地图之地址选择功能
在进行小程序的开发过程中,地图是一个常用的功能,标注地理位置,选择地址,导航等等。本文介绍其中之一的地址选择功能,其它功能后续一一道来。地址选择主要是调用小程序内置的接口:wx.chooseLocation。通过该接口打开选择页面。 调用wx.chooseLocation时注意小程序位置授权问题,没有授权调用该接口会失败。 地址选择详细过程如下: 1、 在小程序页面(.wxml )中添加触发按钮,弹出地图选择页面,地图选择页面是小程序内置的,不需要开发,直调用就可以。 <button bindtap="selectLocation">获取位置</button>//bindtap:绑定js事件属性 <view> <text>{{localinfo.address}}</text>//选择后的地址回调显示 </view> 页面效果如下:
小程序地图之地址选择功能
2、 在小程序的js文件中,添加绑定事件代码,方法名称和bindtop内的名称相同。调用小程序内置地理位置api需要授权,这个要注意。 // 设置绑定事件 Page({ /** * 页面的初始数据 */ data: { localinfo:{} }, //地理位置选择,跳转方法。 tempgetLocal:function(){ //当前对象 var thisBlock = this; //打开地址选择页面 wx.chooseLocation({ //选择成功,执行的回调方法 success: function (res) { console.log(res); var lkinfo={}; lkinfo.latitude= res.latitude; lkinfo.longitude= res.longitude; lkinfo.speed = res.longitude; lkinfo.address = res.address; thisBlock.setData({ localinfo: lkinfo }); } }) }, //页面绑定的选择按钮触发的方法。 selectLocation: function (event) { var thisBlock = this; //判断地理位置权限 wx.getSetting({ success: (res) => { //如果授权,调用接口 if (res.authSetting['scope.userLocation']) { this.tempgetLocal(); }else{ //如果没有授权,跳转到授权页面,选择授权 wx.openSetting({ success: function (dataAu) { if(dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授权成功', icon: 'success', duration: 1000 }) //授权成功,执行地址选择方法 this.tempgetLocal(); } else { wx.showToast({ title: '授权失败', icon: 'none', duration: 1000 }) } } }); } } }); }
}) 效果如下
小程序地图之地址选择功能
选择位置,点击确定按钮后的效果图
小程序地图之地址选择功能
返回的json数据如下: { address:"广东省广州市天河区天府路1号",//详细地址 errMsg:"chooseLocation  k"//提示信息 latitude:23.12463//纬度 longitude:113.36199//经度 name:"广州市天河区政府"//地址别名 }
|