Question

I know how to start it out and I know how to put in the scanners and everything, but in school, I've never really learned about longitude and latitude formulas and how to convert those points into radians. So I'm pretty much stuck on this Java problem. Here is what I have so far:

import java.util.*;

class DistanceCalculator {

    // Radius of the earth in km; this is the class constant.
    public static final double Radius = 6372.795; 

    /**
     * This program computes the spherical distance between two points on the surface of the Earth.
     */

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        intro();

        System.out.print("Longitude (degrees.minutes) ");
        double Longitude = console.nextDouble();
        System.out.print("Latitude (degrees.minutes) ");
        double Latitude = console.nextDouble(); 
    }

    public static double distFrom(double lat1, double lng1, double lat2, double lng2); 
        double Latitude = Math.toRadians(...);  
    }

    public static void intro() {
        System.out.println("This program computes the spherical distance between two points on the surface of the Earth.");
        System.out.println("\tPlease start by entering the longitude and the latitude of location 1.");
    }
}

In Java IDE, they say that Longitude and Latitude points (the ones underneath the intro();) are not used, and I know why, since I haven't really defined them yet. I know I'm missing the formula for longitude and latitude. In my book, it wants me to use the spherical law of cosines, and since I've never learned this at school, no matter how hard I study the formula from the websites I sought out, I don't know how to transfer that into Java language.
Another problem is, how do I transfer degrees and minutes from a longitude/latitude point into radians? Do I have to use Math.toRadians thing? Oh yeah and also, my answer has to be in kilometers.

Updated: The math functions some of you guys are talking about confuses me greatly. In school (I'm a high schooler), even at Math IB SL, my teacher has never taught us how to find long/lat. points...yet. So it's hard for me to grasp. Since the spherical law of cosines formula is online, do I basically just take that formula and convert it into "java language" and plug it into my program?

Was it helpful?

Solution

The key word you need to search for is the "Haversine formula".

An easier to understand method, but one which is not quite so accurate for small distances, is to recall that the angle between two vectors A and B can be calculated using the dot product:

A ⋅ B = |A| * |B| * cos(theta)

so if you convert your polar lat/long pairs into 3D cartesian coordinates (and yes, you'll need to use Math.toRadians(), Math.cos() and Math.sin() to do that, and then calculate the dot product, you'll then get cos(theta), so use Math.acos() to get theta.

You can then work out the distance simply as D = R * theta, where R is the radius of the Earth, and theta remains in radians.

OTHER TIPS

I suggest to read more about WGS84.

Mathematical explanations here.

You may look at this link for the logic.

http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/

Function in PHP... I don't know Java. So some one edit my post. Here is the PHP function:

function getDistanceBetweenPointsNew($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
    $theta = $longitude1 - $longitude2;
    $distance = (sin(deg2rad($latitude1)) *
    sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
    cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $distance = acos($distance);
    $distance = rad2deg($distance);
    $distance = $distance * 60 * 1.1515;
    switch($unit)
    {
        case 'Mi': break;
        case 'Km' : $distance = $distance *1.609344;
    }
    return (round($distance,2));
}

also to get value from MySQL database:

Calculate distance given 2 points, latitude and longitude

I tried to create a java function, I don't know if it work or not.

try this. If any one can help, try edit my java code.

import java.math.BigDecimal;

public static double round(double unrounded, int precision, int roundingMode)
{
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}

public static double distFrom(double lat1, double lng1, double lat2, double lng2, String unit)
{
    double theta = lng1 - lng2;

    double distance = (
        Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
     )+(
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta))
     );
    distance = Math.acos(distance);
    distance = Math.toDeg(distance);
    distance = distance * 60 * 1.1515;

    switch(unit)
    {
        /* Mi = miles, Km = Kilometers */
        case "Mi"   : 
            break;
        case "Km"   : 
            distance = distance *1.609344;
            break;
    }
    distance = round(distance, 2, BigDecimal.ROUND_HALF_UP);
    return distance;
}
     import java.util.*;

       public class SphericalDistance {
public static void main(String[] args){
System.out.println(" This program computes the spherical distance\n between two points, 1 and 2.");
System.out.println(" Please enter the latitude and longitude for \n each point as a pair of integers, degrees \n followed by minutes:");
System.out.print("Latitude 1:");
    Scanner s=new Scanner(System.in);
    double latangledeg = s.nextDouble();
    double latanglemin = s.nextDouble()/60;

    double phideg = latangledeg + latanglemin;
    double phi1 = phideg * Math.PI/180;


    System.out.print("Longitude 1:");

    double lonangledeg = s.nextDouble();
    double lonanglemin = s.nextDouble()/60;

    double lambdadeg = lonangledeg + lonanglemin;
    double lambda1 = lambdadeg * Math.PI/180;


    System.out.println("Latitude 2:");

    double latangledeg2 = s.nextDouble();
    double latanglemin2 = s.nextDouble()/60;

    double phideg2 = latangledeg2 + latanglemin2;
    double phi2 = phideg2 * Math.PI/180;


    System.out.println("Longitude 2:");

    double lonangledeg2 = s.nextDouble();
    double lonanglemin2 = s.nextDouble()/60;

    double lambdadeg2 = lonangledeg2 + lonanglemin2;
    double lambda2 = lambdadeg2 * Math.PI/180;


    double lambdaf = lambda2 - lambda1;
    double angdistance = Math.acos(Math.sin(phi1)*Math.sin(phi2) + Math.cos(phi1)*Math.cos(phi2)*Math.cos(lambdaf));
    System.out.println("Angular Distance = " + angdistance + " radians");
    int distancekm = (int)(angdistance * 6372.795);
    int distancemi = (int) (distancekm * .621371);
    System.out.println("Distance         = " + distancekm + " kilometers");
    System.out.println("Distance         = " + distancemi + " miles");

    s.close();
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top