在自研产品「商图助理」正式全馆普及之后,出现了定位不在范围内的情况,经过埋点后台统计,查看部分机型存在定位偏离,且偏离比较大,起初在限定用户定位范围值设定的比较小,导致这部分用户一直无法使用本系统,最终对实际检测值进行了适中的扩大,下方放出前后端计算两坐标点距离的代码
JS
代码如下
- function GetDistance( 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 ;// EARTH_RADIUS;
- s = Math.round(s * 10000) / 10000;
- return s;
- }
- // 调用 return的距离单位为km
- GetDistance(10.0,113.0,12.0,114.0)
PHP
代码如下
- private final static double EARTH_RADIUS = 6378.137;//地球半径
- private static double rad(double d) {
- return d * Math.PI / 180.0;
- }
- /**
- * 计算两点间距离
* @return double 距离 单位km,精确到米
*/- public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
- double radLat1 = rad(lat1);
- double radLat2 = rad(lat2);
- double a = radLat1 - radLat2;
- double b = rad(lng1) - rad(lng2);
- double 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 * EARTH_RADIUS;
- s = new BigDecimal(s).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
- return s;
- }