微信小程序限定位置范围

1、获取当前位置经纬度

  onLoad: function (options) {
    var that = this;
    campaign_id = campaign_id
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        lat1 = res.latitude,
          lng1 = res.longitude
      }
    })
  }
 

2、通过点击事件打开地图选择位置

site: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        // name    位置名称
        // address    详细地址
        // latitude    纬度,浮点数,范围为 - 90~90,负数表示南纬
        // longitude    经度,浮点数,范围为 - 180~180,负数表示西经
        console.log(res);
        var site_val = res.address;
        lat2 = res.latitude;
        lng2 = res.longitude;
        if (Number(juli(lat1, lng1, lat2, lng2))>0.5){
          wx.showModal({
            title: '温馨提示',
            content: '位置不能离你大于500米',
            success: function (res) {
              if (res.confirm) {
                  that.site()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          });
        }else{
          that.setData({
            site_val: site_val
          });
        }
        console.log('两点之间距离多少km:',juli(lat1, lng1, lat2, lng2));
      }
    })
  },

3、计算两地之间的距离

// 计算两地之间的距离
function juli(lat1, lng1, lat2, lng2) {
  console.log(lat1, lng1, lat2, lng2)
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s
}
 

 

posted @ 2020-07-14 14:57  yuan9580  阅读(2697)  评论(1编辑  收藏  举报