WeChat アプレットは 2 つの緯度と経度に従って距離を取得します

WeChat アプレットは 2 つの緯度と経度に従って距離を取得します

1、世界中で位置情報を取得

// 获取定位信息
function wxGetLocation (config = {
     
     }) {
    
    
  return new Promise((resolve, reject) => {
    
    
    wx.getLocation({
    
    
      // type: 'wgs84',
      type: 'gcj02',
      altitude: false,
      // isHighAccuracy:true,
      ...config,
      success: (res) => {
    
    
        resolve(res)
      },
      fail: (error) => {
    
    
        reject(error)
      },
    });

  })
}
module.exports = {
    
     wxGetLocation }

2、ページ内で使用

import {
    
     wxGetLocation } from '../utils/util'
//计算方法
rad(d) {
    
    
        return d * Math.PI / 180.0;
    },
 // 根据经纬度计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
 getDistances(lat1, lng1, lat2, lng2) {
    
    
     var radLat1 = this.rad(lat1);
     var radLat2 = this.rad(lat2);
     var a = radLat1 - radLat2;
     var b = this.rad(lng1) - this.rad(lng2);
     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;
     var distance = s;
     var distance_str = "";
     if (parseInt(distance) >= 1) {
    
    
         distance_str = distance.toFixed(2) + "km";
     } else {
    
    
         distance_str = (distance * 1000).toFixed(2) + "m";
     }
     let objData = {
    
    
         distance: distance,
         distance_str: distance_str
     }
     return objData
 },
//获取当前经纬度
wxGetLocation().then(
  (res) => {
    
    
    // 经纬度
    var latitude = res.latitude
    var longitude = res.longitude
    this.setData({
    
    
      latitude,
      longitude
    })
    const distance_str = this.getDistances(latitude,longitude,30.169649,120.270846).distance_str;
    distance_str为带单位的距离
        const distance = this.getDistances(latitude,longitude,30.169649,120.270846).distance_str;
    distance为不带单位的小数距离(可用来排序)
  })
  //模拟排序
list.sort((a, b) => {
    
    
        return a.sort - b.sort
    })

この記事があなたのお役に立てれば幸いです

おすすめ

転載: blog.csdn.net/weixin_44255044/article/details/126701458