Calculate the spherical distance between two GeoCoordinates in meters using the Haversine formula. - Android Map

Android examples for Map:Location Distance

Description

Calculate the spherical distance between two GeoCoordinates in meters using the Haversine formula.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot./*from w w w.  ja v a2 s  . c  o m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/
import static java.lang.Math.cos;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import java.util.List;
import android.location.Location;

public class Main{
    /**
     * Calculate the spherical distance between two GeoCoordinates in meters using the Haversine formula.
     * 
     * This calculation is done using the assumption, that the earth is a sphere, it is not though. If you need a higher
     * precision and can afford a longer execution time you might want to use vincentyDistance
     * 
     * @param lon1
     *            longitude of first coordinate
     * @param lat1
     *            latitude of first coordinate
     * @param lon2
     *            longitude of second coordinate
     * @param lat2
     *            latitude of second coordinate
     * 
     * @return distance in meters as a double
     * @throws IllegalArgumentException
     *             if one of the arguments is null
     */
    public static double haversineDistance(double lon1, double lat1,
            double lon2, double lat2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return c * LocationConstants.EQUATORIALRADIUS;
    }
}

Related Tutorials