最近搜索

小程序里面 我想获取 用户当前的经纬度。然后计算与 目标的经纬度 有多少米的距离。或者多少公里。

浏览:7
管理员 2026-03-30 12:17



// 计算两个经纬度坐标之间的距离(米)
calculateDistance(lat1, lng1, lat2, lng2) {
  // 将经纬度转换为弧度
  const radLat1 = lat1 * Math.PI / 180.0
  const radLat2 = lat2 * Math.PI / 180.0
  const a = radLat1 - radLat2
  const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
  
  // 使用Haversine公式计算
  let distance = 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)
  ))
  
  // 地球半径(米)
  const earthRadius = 6378137
  
  // 计算距离(米)
  distance = Math.round(distance * earthRadius)
  
  return distance
}

// 如果需要以公里为单位显示
formatDistance(distance) {
  if (distance < 1000) {
    return `${distance}米`
  } else {
    const km = (distance / 1000).toFixed(2)
    return `${km}公里`
  }
}




联系站长

站长微信:xiaomao0055

站长QQ:14496453