微信小程序地理定位和城市选择列表

2023-03-12,,

1、先获取用户是否授权地理定位,如果没有让其跳转到设置页面手动开启(获取到的位置是经纬度,需要借助其他地图SDK的地址逆解析获取省市区的名字)

getSetting() {
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] == false) {//如果没有授权地理位置
console.log('没有开启地理定位')
wx.showModal({
title: '温馨提示',
content: '您未开启地理定位权限',
success: () => {
wx.openSetting({
success: (res) => {
console.log(res)
res.authSetting = {//打开授权位置页面,让用户自己开启
"scope.userLocation": true
}
}
})
}
})
} else {
//用户开启授权后可直接获取地理位置
wx.authorize({
scope: 'scope.userLocation',
success: () => {
//获取位置后相关操作
this.getLocation();
}
})
}
},
fail:(error) => {
console.log(error)
}
})
},
 //获取地理位置
getLocation() {
wx.getLocation({
type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: (res) => {
console.log(res)
this.setData({
location: res
})
}
})
},

2、城市选择列表

  实现功能:

点击右侧字母区域跳转到对应字母位置 (使用scroll-view的scroll-into-view属性,给他的子元素设置id,scroll-into-view的值即为需要跳转到子元素的id)

<scroll-view scroll-y="true" style="height: 100vh" scroll-into-view="{{scrollId}}" scroll-with-animation="true" enable-back-to-top="true">
<view wx:for="{{ list }}" wx:key="key">
<view id="{{ item.key }}" data-id="{{ item.key }}" bindtap="selectId">{{ item.value }}</view>
</view> selectId(e) {
this.setData({
scrollId: e.currentTarget.dataset.id
})
}

滚动反显右侧字母区,滚动到B,右侧亮起 (获取每一个子元素的top顶部距离,利用scroll-view的bindscroll属性监听滚动事件,判断其scrollTop和每一个元素比较,相近的即可,如果使用点击事件进行第一步,则不滚动监听)

<scroll-view bindscroll="{{ isSelected ? 'scroll' : ''}}"></scroll-view>
scroll(e) {
console.log(e.detail.scrollTop)
} // 获取顶部距离和子元素的顶部距离(一定要写in,否则获取到的是null)
let query = wx.createSelectorQuery().in(this);
// 获取单个元素
query.select('.city-letter').boundingClientRect(r => {
console.log(r.top, r.height)
}).exec();
// 获取多个元素,rect是一个数组
query.selectAll('.city-item').boundingClientRect(rect => {
console.log(rect) }).exec();

在字母区滑动选择 (使用view的bindtouchstart、catchtouchmove、bindtouchend滑动事件,记录在首字母区域滑动的距离,获取首字母区域的高度和顶部距离,获得数组下标 = (滑动距离-顶部距离) / 区域高度 * 字母数组长度)
因滑动事件和点击事件都放在同一个view上会有冲突,执行顺序是touchstart - touchend - tap,所以点击事件时判断pageY和touchstart的PageY,如果相等就是执行的点击事件,不需要执行滑动事件

 注意:scrolllId、滚动对应的变量、滑动时的变量是分设了三个变量,需要互相清空,注意限制条件

微信小程序地理定位和城市选择列表的相关教程结束。

《微信小程序地理定位和城市选择列表.doc》

下载本文的Word格式文档,以方便收藏与打印。