Calculates the bearing of the two Locations supplied and returns the Angle in the following (GPS-likely) manner: N:0?, E:90?, S:180?, W:270?. - Android Map

Android examples for Map:GPS

Description

Calculates the bearing of the two Locations supplied and returns the Angle in the following (GPS-likely) manner: N:0?, E:90?, S:180?, W:270?.

Demo Code


import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.graphics.Point;
import android.graphics.Rect;
import android.location.Location;
import android.os.Environment;
import android.util.Log;

public class Main{
    /**/*from ww w  .j av  a2s  .com*/
     * Calculates the bearing of the two Locations supplied and returns the
     * Angle in the following (GPS-likely) manner: <br />
     * <code>N:0?, E:90?, S:180?, W:270?</code>.
     * 
     * @param before
     *            the before
     * @param after
     *            the after
     * 
     * @return the float
     */
    static public float calculateBearing(final Location before,
            final Location after) {
        final Point pBefore = location2Point(before);
        final Point pAfter = location2Point(after);

        final float res = -(float) (Math.atan2(pAfter.y - pBefore.y,
                pAfter.x - pBefore.x) * 180 / MathematicalConstants.PI) + 90.0f;

        if (res < 0) {
            return res + 360.0f;
        } else {
            return res;
        }
    }
    /**
     * Converts an {@link Location} to an {@link Point}.
     * 
     * @param aLocation
     *            the a location
     * 
     * @return the point
     */
    static public Point location2Point(final Location aLocation) {
        return new Point((int) (aLocation.getLongitude() * 1E6),
                (int) (aLocation.getLatitude() * 1E6));
    }
}

Related Tutorials