关于微信小程序地图缩放显示的问题,官方的api在安卓手机上无效,花了九牛二虎之力写了一个?

624 阅读1分钟

----地图模式-全览:两个经纬度并联线计算两点距离----

在微信小程序中,要实时获取设备的GPS定位信息,点击地图设置目标点,并标点连线显示出来,大多数人肯定都是先用marker标记是不是? 没错--我也是,效果图如下

image.png

但是同样的问题来了,在安卓机上时间长会出现多个重影,飞机,线,目标点, 只能另行出路了接下来就是画布(canvas)

Canvas,接下来就是经纬度转屏幕坐标了(这个就不说了)

重点来了!!!!!

怎么在如何距离的时候将地图缩放到想要的层级?原生api无效,# MapContext.includePoints

在我组长的帮助下我搞了一套地图底层比例尺缩放的方法代码,我放下面了,自己看吧

// 
  coordToMercator(coord) {
    let lng = coord.lng / 360 + 0.5
    let lat = coord.lat
    lat = 0.5 - (Math.log(Math.tan((Math.PI / 4.0) + (Math.PI / 2.0) * lat / 180.0)) / Math.PI) / 2.0
    lat = this.qBound(0.0, lat, 1.0)
    return {
      lng,
      lat
    }
  },
  //
  qBound(min, val, max) {
    return Math.max(min, Math.min(val, max))
  },
  realmod(a, b) {
    return a - Math.floor(a / b) * b
  },
  mercatorToCoord(mercator) {
    let fx = mercator.x;
    let fy = mercator.y;
    if (fy < 0.0)
      fy = 0.0;
    else if (fy > 1.0)
      fy = 1.0;
    let lat = 0.0;
    if (fy == 0.0)
      lat = 90.0;
    else if (fy == 1.0)
      lat = -90.0;
    else
      lat = (180.0 / Math.PI) * (2.0 * Math.atan(Math.exp(Math.PI * (1.0 - 2.0 * fy))) - (Math.PI / 2.0));

    let lng = 0.0;
    if (fx >= 0) {
      lng = this.realmod(fx, 1.0);
    } else {
      lng = this.realmod(1.0 - this.realmod(-1.0 * fx, 1.0), 1.0);
    }
    lng = lng * 360.0 - 180.0;
    return {
      lat,
      lng
    }
  },
  //传入的两个对象一个是左上角 一个是右上角的经纬度坐标,是形成矩形的左右上角,
  getChangeScale(coord, coord1) {
    let topLeftPoint = this.coordToMercator(coord)
    let bottomRightPoint = this.coordToMercator(coord1)
    //console.log(topLeftPoint, bottomRightPoint);
    if (bottomRightPoint.lng < topLeftPoint.lng) // crossing the dateline
      bottomRightPoint.lng = bottomRightPoint.lng + 1.0;
    let center = {
      x: (topLeftPoint.lng + bottomRightPoint.lng) / 2,
      y: (topLeftPoint.lat + bottomRightPoint.lat) / 2
    };
    center.x = center.x > 1.0 ? center.x - 1.0 : center.x;
    let centerCoordinate = this.mercatorToCoord(center)
    const w = Math.pow(2.0, this.data.scale) * 256;
    let bboxWidth = (bottomRightPoint.lng - topLeftPoint.lng) * w;
    let bboxHeight = (bottomRightPoint.lat - topLeftPoint.lat) * w;
    if (bboxHeight == 0.0 && bboxWidth == 0.0) {
      return;
    }
    //padding是边距
    let padding =50
    let zoomRatio = Math.max(bboxWidth / (this.data.mapWidth - padding), bboxHeight / (this.data.mapHeight - padding));
    zoomRatio = Math.log(zoomRatio) / Math.log(2.0)
    let newZoom = Math.max(3, this.data.scale - zoomRatio)
    return {
      newZoom,
      centerCoordinate
    }
  },

然后将中心坐标放在中心,设置层级就可,希望可以帮助到各位gym!