微信小程序获取当前位置 地图定位导航
小程序获取当前位置,回到当前位置,地图定位,导航
效果

因为小程序更新了获取地理位置API接口,需要先在app.json中配置一下permission字段 ,不然会报微信小程序getLocation 需要在app.json中声明permission字段
app.json: (不知道具体位置可以看这里,这里有整个app.json的配置)
'permission': {'scope.userLocation': {'desc': '你的位置信息将用于小程序位置接口的效果展示'}}
wxml:
<!--pages/map/map.wxml--><!-- 这是地图部分 --><view class='map_container'><map class='map' longitude='{{longitude}}' latitude='{{latitude}}' scale='{{scale}}' markers='{{markers}}' controls='{{controls}}' bindcontroltap='bindcontroltap' polyline='{{polyline}}' circles='{{circles}}' bindmarkertap='bindmarkertap' bindcontroltap='bindcontroltap'show-location></map></view><!-- 以下是导航部分 --><view class='list-guide'><!-- 这里的坐标本应该是从服务器获取数据的,这时丈先写死在页面上了 --><view bindtap='onGuideTap' data-latitude='39.92392' data-longitude='116.411885' data-bankName='最高人民检察院'><image src='/images/banklist/daohang.png' class='list-guide-imgae'></image><text class='list-guide-text'>导航</text></view><view bindtap='onbankTap' data-bankId='{{item.BANK_ID}}'><image src='/images/banklist/xiangqing.png' class='list-guide-imgae'></image><text class='list-guide-text'>详情</text></view></view>
宽度不是满屏,所以加个样式
wxss:
/* pages/map/map.wxss */.map_container {height: 260px;width: 100%;}.map {height: 100%;width: 100%;}.list-guide{display: flex;flex-direction: row;justify-content:space-around;border-top: 1px solid #ededed;height: 80rpx;}.list-guide-imgae{height: 70rpx;width: 70rpx;margin-right: 20px;vertical-align: middle;}.list-guide-text{vertical-align: middle;line-height: 90rpx;font-size: 35rpx;}
下面就是最重要的JS部分了()
JS:
// pages/map/map.jsPage({/*** 页面的初始数据*/data: {addmissage: '选的位置',// markers Array标记点stitle:'故宫',latitude: '',longitude: '',scale: 14,markers: [],//controls控件 是左下角圆圈小图标,用户无论放大多少,点这里可以立刻回到当前定位(控件(更新一下,即将废弃,建议使用 cover-view 代替))controls: [{id: 1,iconPath: '../../images/img/controls.png',position: {left: 15,top: 260 - 50,width: 40,height: 40},clickable: true}],distanceArr: []},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {var that = this//获取当前的地理位置、速度wx.getLocation({type: 'wgs84', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标success: function (res) {//赋值经纬度that.setData({latitude: res.latitude,longitude: res.longitude,})}})},//controls控件的点击事件bindcontroltap(e) {var that = this;if (e.controlId == 1) {that.setData({latitude: this.data.latitude,longitude: this.data.longitude,scale: 14,})}},//导航onGuideTap: function (event) {var lat = Number(event.currentTarget.dataset.latitude);var lon = Number(event.currentTarget.dataset.longitude);var bankName = event.currentTarget.dataset.bankname;console.log(lat);console.log(lon);wx.openLocation({type: 'gcj02',latitude: lat,longitude: lon,name: bankName,scale: 28})},})
项目下载在这里(只是地图部份,也有删减,非实际项目全部)
下面是我实际项目中的截图


赞 (0)
