uni-app develops WeChat applet to obtain location information and calculate distance

1. uniapp project

 

Open the configuration file manifest.json of the uniapp project and select "Source Code View".

/* 小程序特有相关 */
"mp-weixin": {
	"appid": "你的开发者id",
	"setting": {
		"urlCheck": true,
		"es6": true,
		"postcss": true,
		"minified": true
	},
	"usingComponents": true,
	"permission": {
		"scope.userLocation": {
			"desc": "你的位置信息将用于小程序位置接口的效果展示"
		}
	},
	"requiredPrivateInfos": ["getLocation", "chooseLocation"]
},

2. How to activate the corresponding positioning interface on the WeChat public platform?

Open the WeChat public platform , go to the left menu [Develop] - [Development Management] - [Interface Settings] to activate the interface you need.

How to apply:

1. Upload the screenshot of the page that needs to be positioned for this project;

2. Fill in the purpose of obtaining positioning;

3. Fill in the code to obtain the location where you need to use it

uni.getLocation({
								type: 'wgs84',
								success: function (res) {
									console.log('当前位置的经度:' + res.longitude);
									console.log('当前位置的纬度:' + res.latitude);
								},
								fail:function(err){
									console.log('uni.getLocation',err)
								}
							});

4. Implementation of the method of calculating distance

//计算距离的方法实现
function rad(d) {
    return d * Math.PI / 180.0;
}


// 根据经纬度计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
function getDistances(lat1, lng1, lat2, lng2) {

    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - 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; // EARTH_RADIUS;
    // 输出为公里
    s = Math.round(s * 10000) / 10000;

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
        // distance_str = distance.toFixed(1) + "km";
        distance_str = distance.toFixed(2) + "km";
    } else {
        // distance_str = distance * 1000 + "m";
        distance_str = (distance * 1000).toFixed(2) + "m";
    }

    //s=s.toFixed(4);

    // console.info('距离是', s);
    // console.info('距离是', distance_str);
    // return s;
    
    //小小修改,这里返回对象
    let objData = {
        distance: distance,
        distance_str: distance_str
    }
    return objData
}

Guess you like

Origin blog.csdn.net/a2367994141/article/details/129528320