视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
微信小程序地图(map)组件点击(tap)获取经纬度的方法
2020-11-27 22:02:14 责编:小采
文档


微信小程序中使用地图(map)组件,通过点击(tap)获取经纬度,按照官方的回应,暂时是没法做到的,从地图组件API多有残缺判断,怀疑是个实习生干的...

做个变通,适用性有限,请大家参考。基本思路就是在地图上铺满一层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()
 }
})

效果如图

下载本文
显示全文
专题