用java 计算两点之间的距离

package com.java.tool.until;import java.awt.geom.Point2D;
import java.math.BigDecimal;/*** @desc 地理位置计算工具类* @author xl* @date 2019/12/26 11:12*/
public class MapUtils {private static final double EARTH_RADIUS = 6371393; // 平均半径,单位:m/*** 通过AB点经纬度获取距离* @param pointA A点(经,纬)* @param pointB B点(经,纬)* @return 距离(单位:米)*/public static double getDistance(Point2D pointA, Point2D pointB) {// 经纬度(角度)转弧度。弧度用作参数,以调用Math.cos和Math.sindouble radiansAX = Math.toRadians(pointA.getX()); // A经弧度double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度double radiansBX = Math.toRadians(pointB.getX()); // B经弧度double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度// 公式中“cosβ1cosβ2cos(α1-α2)+sinβ1sinβ2”的部分,得到∠AOB的cos值double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)+ Math.sin(radiansAY) * Math.sin(radiansBY);
//        System.out.println("cos = " + cos); // 值域[-1,1]double acos = Math.acos(cos); // 反余弦值
//        System.out.println("acos = " + acos); // 值域[0,π]
//        System.out.println("∠AOB = " + Math.toDegrees(acos)); // 球心角 值域[0,180]return new BigDecimal(EARTH_RADIUS * acos/1000).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue(); // 最终结果}public static  String getDistance99(Point2D pointA, Point2D pointB){double distance = getDistance(pointA,pointB);if ( distance > 99 ){return "> 99km";}else {return String.valueOf(distance)+"km";}}public static void main(String[] args) {// 北京 东单地铁站Point2D pointDD = new Point2D.Double(116.425249, 39.914504);// 北京 西单地铁站Point2D pointXD = new Point2D.Double(116.382001, 39.913329);// System.out.println(getDistance(pointDD, pointXD));String s =  getDistance99(pointDD, pointXD);System.out.println(s);// 北京 天安门Point2D pointTAM = new Point2D.Double(116.403882, 39.915139);// 广州 越秀公园Point2D pointGZ = new Point2D.Double(113.272422,23.147387);String str =  getDistance99(pointTAM, pointGZ);System.out.println(str);// 四川大学Point2D pointSCDX = new Point2D.Double(104.090539,30.636951);// 成都南站Point2D pointCDNZ = new Point2D.Double(104.074238,30.612572);System.out.println(getDistance(pointSCDX, pointCDNZ));System.out.println();}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部