37

计算某地点到当前定位的距离,并重新对数组进行排序 - - SegmentFault 思否

 4 years ago
source link: https://segmentfault.com/a/1190000020888309
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

计算某地点到当前定位的距离,并重新对数组进行排序

1.获取当前定位
getLocal() {
    var that = this
    uni.getLocation({
        type: 'wgs84',
        success: function (res) {
           // 获取到经纬度后,调用 computeDistance对数组进行排序
           that.computeDistance(res.latitude,res.longitude)
        }
  )}          
},
2.计算距离然后排序

(1)百度到其他大神的计算两个经纬度距离的方法

/**
 * js获取两个经纬度之间的距离
 * @param lat1 第一点的纬度
 * @param lng1 第一点的经度
 * @param lat2 第二点的纬度
 * @param lng2 第二点的经度
 * @returns {Number}
 */
distance(la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2);
    return s;
},

(2) 调用接口获取到医院的列表,然后取得每个医院的经纬度与用户当前定位的经纬度进行计算

computeDistance(latitude,longitude) {
    var that = this
    // 获取医院列表
    uni.request({
        url: app.apiUrl + 'small/index/index',
        success: (res) => {
            that.poslist = res.data.poslist
            // 计算医院列表中经纬度与当前的距离,并添加distance属性到数组的元素中 key:distance vaule: 距离
            for (let i=0; i<that.poslist.length; i++) {
            // 调用distance的方法计算两点的距离,并把距离值赋值给医院数组对象中的新属性distance
                that.poslist[i].distance = (that.distance(latitude,longitude,that.poslist[i].latitude,that.poslist[i].longitude))
                // 根据新属性值distance对数组重新排序,距离最短排前面
                that.poslist.sort(function(a,b){
                    return a.distance-b.distance;
                })
            }
        }
    })
},

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK