MapHelper.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package cn.com.ty.lift.common.utils;
  2. /**
  3. * 通过地图上的两个坐标计算距离(Java版本)
  4. * Add by 成长的小猪(Jason.Song) on 2017/11/01
  5. * http://blog.csdn.net/jasonsong2008
  6. */
  7. public class MapHelper {
  8. /**
  9. * 经纬度转化成弧度
  10. * Add by 成长的小猪(Jason.Song) on 2017/11/01
  11. * http://blog.csdn.net/jasonsong2008
  12. *
  13. * @param d 经度/纬度
  14. * @return
  15. */
  16. private static double rad(double d) {
  17. return d * Math.PI / 180.0;
  18. }
  19. /**
  20. * 计算两个坐标点之间的距离
  21. * Add by 成长的小猪(Jason.Song) on 2017/11/01
  22. * http://blog.csdn.net/jasonsong2008
  23. *
  24. * @param firstLatitude 第一个坐标的纬度
  25. * @param firstLongitude 第一个坐标的经度
  26. * @param secondLatitude 第二个坐标的纬度
  27. * @param secondLongitude 第二个坐标的经度
  28. * @return 返回两点之间的距离,单位:公里/千米
  29. */
  30. public static double getDistance(double firstLatitude, double firstLongitude,
  31. double secondLatitude, double secondLongitude) {
  32. double firstRadLat = rad(firstLatitude);
  33. double firstRadLng = rad(firstLongitude);
  34. double secondRadLat = rad(secondLatitude);
  35. double secondRadLng = rad(secondLongitude);
  36. double a = firstRadLat - secondRadLat;
  37. double b = firstRadLng - secondRadLng;
  38. //地球半径
  39. double earthRadius = 6378.137;
  40. double cal = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(firstRadLat)
  41. * Math.cos(secondRadLat) * Math.pow(Math.sin(b / 2), 2))) * earthRadius;
  42. return Math.round(cal * 10000d) / 10000d;
  43. }
  44. /**
  45. * 计算两个坐标点之间的距离
  46. * Add by 成长的小猪(Jason.Song) on 2017/11/01
  47. * http://blog.csdn.net/jasonsong2008
  48. *
  49. * @param firstPoint 第一个坐标点的(纬度,经度) 例如:"31.2553210000,121.4620020000"
  50. * @param secondPoint 第二个坐标点的(纬度,经度) 例如:"31.2005470000,121.3269970000"
  51. * @return 返回两点之间的距离,单位:公里/千米
  52. */
  53. public static double GetPointDistance(String firstPoint, String secondPoint) {
  54. String[] firstArray = firstPoint.split(",");
  55. String[] secondArray = secondPoint.split(",");
  56. double firstLatitude = Double.parseDouble(firstArray[0].trim());
  57. double firstLongitude = Double.parseDouble(firstArray[1].trim());
  58. double secondLatitude = Double.parseDouble(secondArray[0].trim());
  59. double secondLongitude = Double.parseDouble(secondArray[1].trim());
  60. return getDistance(firstLatitude, firstLongitude, secondLatitude, secondLongitude);
  61. }
  62. }