小程序地图经纬度和屏幕坐标互转

2021-08-25  本文已影响0人  姬歌

地图坐标和屏幕坐标互转方式:

MapContext.fromScreenLocation(Object object):该API无法传值、无任何响应
MapContext.getCenterLocation(Object object):API可用
MapContext.toScreenLocation(Object object):官方文档有错,object应包含{latitude: xxx, longitude: xxx}两项内容

在获取地图中心点坐标例子:

1、在地图中心点显示一个图片(大头针)
map_center.png
<map id="myMap" class="myMap" scale="{{scale}}" min-scale="8" longitude="{{longitude}}" latitude="{{latitude}}" 
markers="{{markers}}" polyline="{{polyline}}" polygons="{{businessZones}}" show-location="true" 
bindmarkertap="tapMarker" bindregionchange="regionDidChange">
    <!-- map content -->
    <cover-image class="manpCenter" src="../../../images/home/map/map_center.png"></cover-image>
</map>

wxss

.customContainer {
  margin-top: 0px;
  width: 100vmin;
  height: 100vmax;
  display: flex;
  flex-direction: column;
}

.myMap {
  width: 100%;
  height: 100%;
}

.manpCenter {
  width: 48rpx;
  height: 77rpx;
  position: absolute;
  left: calc(50% - 24rpx);
  top: calc(50% - 77rpx);
}

js

onLoad: function (options) {
    this.mapCtx = wx.createMapContext('myMap')
},
// 如果仅有地图缩放但没有平移,并不会触发此方法。目前未发现有能够监控scale变化的api。如果一定要监控缩放,
// 只能自己设置定时器,监控this.mapCtx.getScale(Object)。但用户体验可能也很差。
// MapContext官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/map/MapContext.getScale.html
regionDidChange(e) {
    if (e.type == 'end') {    // 注意,这个事件的type至少有2种类型,'begin'和'end',我们滑动一下地图,会有2次响应。但我们只关注'end'!!!
        this.getCenterLocation()
    }
},

getCenterLocation: function () {
    this.mapCtx.getCenterLocation({
      success: function(res){
        // console.log(res)
        console.log(res.latitude + ',' + res.longitude)
      }
    })
 }, 

上一篇 下一篇

猜你喜欢

热点阅读