分享

JAVA计算两个经纬度之间的距离

 张天麒 2017-06-05

1、只不过是封装好的一个计算方法,计算的方式也就是上学时就学过的定理,老规矩直接贴代码,主要是方便实用,计算结果单位:米

  1. public class MapUtils {  
  2.     //private static double EARTH_RADIUS = 6378.137;  
  3.     private static double EARTH_RADIUS = 6371.393;  
  4.     private static double rad(double d)  
  5.     {  
  6.        return d * Math.PI / 180.0;  
  7.     }  
  8.   
  9.     /** 
  10.      * 计算两个经纬度之间的距离 
  11.      * @param lat1 
  12.      * @param lng1 
  13.      * @param lat2 
  14.      * @param lng2 
  15.      * @return 
  16.      */  
  17.     public static double GetDistance(double lat1, double lng1, double lat2, double lng2)  
  18.     {  
  19.        double radLat1 = rad(lat1);  
  20.        double radLat2 = rad(lat2);  
  21.        double a = radLat1 - radLat2;      
  22.        double b = rad(lng1) - rad(lng2);  
  23.        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +   
  24.         Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));  
  25.        s = s * EARTH_RADIUS;  
  26.        s = Math.round(s * 1000);  
  27.        return s;  
  28.     }  
  29.       
  30.       
  31.       
  32.     public static void main(String[] args) {  
  33.         System.out.println(MapUtils.GetDistance(29.490295,106.486654,29.615467,106.581515));  
  34.     }  
  35. }  


2、顺带提一下百度地图提供的计算两地经纬度的方法,很简单的一句话调用,可以自行去看百度地图API试试,计算结果单位:米

  1. var map = new BMap.Map("allmap");  
  2. var pointA = new BMap.Point(106.486654,29.490295);  // 点坐标A  
  3. var pointB = new BMap.Point(106.581515,29.615467);  // 点坐标B  
  4. alert(map.getDistance(pointA,pointB)).toFixed(2));  //toFixed(2)意思为保留小数点后两位  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多