實現效果如下
1.頁面加載時,根據getLocation方法獲取用戶當前經緯度獲取20條醫院位置信息
2.頁面滑動時,根據滑動到的經緯度再次獲取20條醫院位置信息
獲取到的醫院位置信息
實現方法如下
1.在.wxml中添加觸發滑動的方法bindregiοnchange=“onMapRegionChange”
<map id="map" class="map" scale="{{scale}}" markers="{{markers}}" latitude="{{lat}}" show-location longitude="{{lng}}" enable-satellite="{{mapChange}}" bindmarkertap="onMarkerTap" bindregionchange="onMapRegionChange">
2.在.js中
Page({data: {markers: [], //覆蓋物txKey: "你的騰訊地圖key", //騰訊地圖keyregionChanged: false // 地圖區域是否發生變化的標志},onLoad(options) {let that = this//獲取用戶當前位置wx.getLocation({type: 'gcj02',success: function (res) {console.log('用戶已授權位置權限,經緯度:' + res.longitude, res.latitude);that.setData({lat: res.latitude,lng: res.longitude})//調用地點搜索方法,把用戶當前位置經緯度傳遞給該方法that.getHospitalLoacal(res.longitude,res.latitude)}})},//觸發滑動方法onMapRegionChange: function (e) {if (e.type === 'end') {this.setData({regionChanged: false});//獲取到滑動的經緯度,傳遞給該方法this.getHospitalLoacal(e.detail.centerLocation.longitude, e.detail.centerLocation.latitude);}},//地點搜索方法getHospitalLoacal(lng,lat){console.log("搜索醫院···")// 使用騰訊地圖API進行關鍵詞搜索wx.request({url: 'https://apis.map.qq.com/ws/place/v1/search',data: {keyword: '醫院', // 搜索關鍵詞為“醫院”/**格式:boundary=nearby(lat,lng,radius[, auto_extend])子參數:lat,lng:搜索中心點的經緯度,格式順序為緯度在前,經度在后radius:搜索半徑,單位:米,取值范圍:10到1000auto_extend:[可選] 當前范圍無結果時,是否自動擴大范圍,取值:0 不擴大1 [默認] 自動擴大范圍(依次按照按1公里、2公里、5公里,最大到全城市范圍搜索)*/boundary: 'nearby('+lat+','+lng+',1000,1)',key: this.data.txKey,page_size: 20,//每頁條目數,最大限制為20條,默認為10條page_index: 1 //第x頁,默認第1頁},success: res => {if (res.data.status === 0) {let hospitals = res.data.data.map(item => {return {id: item.id,longitude: item.location.lng,latitude: item.location.lat,title: item.title,iconPath: '/images/hospital.png', // 自定義標記的圖標width: 30,height: 30};});this.setData({markers: hospitals});} else {console.error('地圖API請求失敗:', res.data.message);}},fail: error => {console.error('地圖API請求失敗:', error);}});}
})
如果本文對你有幫助,記得一鍵三連哦,你的支持和鼓勵就是我最大的動力!^_^