知识学堂 > 课程 > 微信小程序地图定位距离计算

微信小程序地图定位距离计算

发布日期:2023/11/10 来源:聚恒【返回】

  huoqufanwei: function (params) {
    var that = this;
    wx.getLocation({
      isHighAccuracy: true,
      type: 'gcj02',//用腾讯地图坐标拾取器才能和这个对上
      success: function (res) {
        var latitude = res.latitude;
        console.log("当前纬度 = " + latitude);
        var longitude = res.longitude;
        console.log("当前经度 = " + longitude);
        var speed = res.speed;
        console.log("当前速度" + speed);
        var accuracy = res.accuracy;
        console.log("当前精确度" + accuracy);
        that.setData({
          juli2: that.getDistance(latitude, longitude, 31.175808,121.180847),
          ZXlatitude:latitude,
          ZXlongitude:longitude,
          ZXscale:1
        })

      }
    })
  },
  //距离计算
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2+ Math.cos(rad1* Math.cos(rad2* Math.pow(Math.sin(b / 2), 2)));
    return distance;
  }

<view class="Wrap">
  <map id="dituclass='maplongitude='{{ZXlongitude}}' latitude='{{ZXlatitude}}' scale='{{scale}}'
   bindpoitap="bindcontroltapbindcallouttap='bindcallouttap1show-location>
  </map>
<view>{{juli2}}</view>
<view bind:tap="huoqufanwei">定位</view>
</view>