微信小程序中使用地圖(map)組件,經過點擊(tap)獲取經緯度,按照官方的迴應,暫時是無法作到的,從地圖組件API多有殘缺判斷,懷疑是個實習生乾的...git
作個變通,適用性有限,請你們參考。基本思路就是在地圖上鋪滿一層marker,從而經過點擊marker得到經緯度。小程序
<map id="map" longitude="102.324520" latitude="40.099994" scale="4" bindcontroltap="controltap" polygons="{{polygons}}" bindregionchange="regionchange" markers="{{markers}}" bindmarkertap="markertap" show-location style="width: 100%; height: 700px;"></map>
const app = getApp() const markersize = 30 function range(start, edge, step) { for (var ret = []; (edge - start) * step > 0; start += step) { ret.push(start); } return ret; } function markers(northeast, southwest, scale, width, height) { const markerslng = (northeast.longitude - southwest.longitude) * markersize / width const markerslat = (northeast.latitude - southwest.latitude) * markersize / height const maxlon = northeast.longitude const minlon = southwest.longitude const maxlat = northeast.latitude const minlat = southwest.latitude const lons = range(minlon, maxlon, markerslng) const lats = range(minlat, maxlat, markerslat) let _markers = [] lons.forEach((lon, i) => { lats.forEach((lat, j) => { _markers.push({ id: lon + ',' + lat, latitude: lat, longitude: lon, iconPath: '/marker.png', alpha: 0.1, //將圖片設置爲透明,經過開發者工具看不出效果,但真機是有效果的 width: markersize, height: markersize }) }) }) return _markers } Page({ data: { polygons: [], controls: [{ id: 1, position: { left: 0, top: 300 - 50, width: 50, height: 50 }, clickable: true }], markers: [] }, createMarkers() { this.mapCtx = wx.createMapContext('map') const query = wx.createSelectorQuery() const map = query.select('#map').boundingClientRect() let that = this that.mapCtx.getRegion({ success(res1) { that.mapCtx.getScale({ success(res2) { query.exec((res) => { let width = res[0].width; let height = res[0].height; let _markers = markers(res1.northeast, res1.southwest, res2.scale, width, height) that.data.markers = _markers that.setData(that.data) }) } }) } }) }, regionchange(e) { this.createMarkers() }, markertap(e) { console.log(e.markerId) }, controltap(e) { console.log(e.controlId) }, onReady(e) { this.createMarkers() } })
效果如圖微信小程序