Computes the distance of two points on a sphere. - Java java.lang

Java examples for java.lang:Math Geometry Distance

Description

Computes the distance of two points on a sphere.

Demo Code


//package com.java2s;

public class Main {
    /**/*from   www .j  av  a 2s  .co  m*/
     * Computes the distance of two points on a sphere.
     * 
     * @param latA The latitude of point A in degrees.
     * @param lonA The longitude of point A in degrees.
     * @param latB The latitude of point B in degrees.
     * @param lonB The longitude of point B in degrees.
     * @param radius The radius of the sphere.
     * @return The distance.
     */
    public static double sphereDistance(final double latA,
            final double lonA, final double latB, final double lonB,
            final double radius) {
        final double dLat = Math.toRadians(latB - latA) * .5;
        final double dLon = Math.toRadians(lonB - lonA) * .5;
        final double rLatA = Math.toRadians(latA);
        final double rLatB = Math.toRadians(latB);
        final double a = Math.sin(dLat) * Math.sin(dLat) + Math.sin(dLon)
                * Math.sin(dLon) * Math.cos(rLatA) * Math.cos(rLatB);
        final double c = Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return 2 * radius * c;
    }
}

Related Tutorials