Java开发之百度地图2 :计算两地之间的距离

package com.***********.util;

import java.awt.geom.Point2D;

/**
 * 百度工具类
 * 
 * @author qyx
 *
 */
public class BaiduUtil2 {

	public static void main(String[] args) {
		try {
			// 太原
			Point2D pointDD = new Point2D.Double(112.53, 37.87);
			// 上海
			Point2D pointXD = new Point2D.Double(121.48, 31.22);
			System.out.println("太原-上海:"+getDistance(pointDD, pointXD));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	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.sin
		double 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
		double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
				+ Math.sin(radiansAY) * Math.sin(radiansBY);
		double acos = Math.acos(cos); // 反余弦值
		return EARTH_RADIUS * acos; // 最终结果
	}

}

 

你可能感兴趣的:(百度地图,Java)