Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.location.Location;

public class Main {
    private static int EARTH_RADIUS_KM = 6371;

    /**
     * Computes the distance in meters between two points on Earth.
     *
     * @param lat1 Latitude of the first point
     * @param lon1 Longitude of the first point
     * @param lat2 Latitude of the second point
     * @param lon2 Longitude of the second point
     * @return Distance between the two points in meters.
     */
    public static double distance(double lat1, double lon1, double lat2, double lon2) {
        double lat1Rad = Math.toRadians(lat1);
        double lat2Rad = Math.toRadians(lat2);
        double deltaLonRad = Math.toRadians(lon2 - lon1);

        return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad)
                + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM * 1000;
    }

    /**
     * Computes the distance in meters between two points on Earth.
     *
     * @param p1 First point
     * @param p2 Second point
     * @return Distance between the two points in meters.
     */
    public static double distance(Location p1, Location p2) {
        double lat1 = p1.getLatitude();
        double lon1 = p1.getLongitude();
        double lat2 = p2.getLatitude();
        double lon2 = p2.getLongitude();

        return distance(lat1, lon1, lat2, lon2);
    }
}