Calculates distance between locations in miles. - Android java.lang

Android examples for java.lang:Math

Description

Calculates distance between locations in miles.

Demo Code


//package com.java2s;

public class Main {
    /***//from w  w w. ja v a  2  s . co m
     * Calculates distance between locations in miles.
     * 1 mile = 1609.344 meters
     * @param startLat
     * @param startLong
     * @param endLat
     * @param endLong
     * @return
     */
    public static double distFrom(double startLat, double startLong,
            double endLat, double endLong) {

        double earthRadius = 6371;
        double dLat = Math.toRadians(endLat - startLat);
        double dLng = Math.toRadians(endLong - startLong);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(startLat))
                * Math.cos(Math.toRadians(endLat)) * Math.sin(dLng / 2)
                * Math.sin(dLng / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double dist = earthRadius * c;//in miles
        //Log.v("Safecell :"+"dist", dist+"");

        return (dist * .621371192);
    }
}

Related Tutorials