001/*
002 * Copyright 2006 Marc Wick, geonames.org
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 */
017package org.geonames.utils;
018
019import static java.lang.Math.atan2;
020import static java.lang.Math.cos;
021import static java.lang.Math.sin;
022import static java.lang.Math.toDegrees;
023import static java.lang.Math.toRadians;
024
025/**
026 * compass bearing from the first point to the second point in degrees.
027 * 
028 * @author Marc Wick
029 */
030public class Bearing {
031
032        /**
033         * Returns the direction from the first point to the second point in
034         * degrees. The direction is the clockwise angle between the magnetic north
035         * and the direction from point1 to point2
036         * 
037         * @param lat1
038         * @param lng1
039         * @param lat2
040         * @param lng2
041         * @return
042         */
043        // http://www.movable-type.co.uk/scripts/latlong.html
044        public static double calculateBearing(double lat1, double lng1,
045                        double lat2, double lng2) {
046                double dLon = toRadians(lng2 - lng1);
047                lat1 = toRadians(lat1);
048                lat2 = toRadians(lat2);
049                double y = sin(dLon) * cos(lat2);
050                double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
051                double brng = toDegrees(atan2(y, x));
052                return (brng + 360) % 360;
053        }
054}