QuestionAsk Questions?

View Answers

August 19, 2009 at 12:32 PM

Hi Friend,

We are providing you a code that will prompt the user to enter the latitude and longitude coordinates of the source and destination and accordingly return the distance between them.

import java.util.*;

public class CalculateDistance{

public static void main(String args[]){

System.out.println("Enter the Longitude and Latitude of Source location:");

Scanner input=new Scanner(System.in);

double lat1=input.nextDouble();

double long1=input.nextDouble();

System.out.println("Enter the Longitude and Latitude of destination location:");

double lat2=input.nextDouble();

double long2=input.nextDouble();

CalculateDistance cal=new CalculateDistance();

double dist=cal.distance( lat1, -long1 ,lat2 , -long2, 'K');

System.out.println(dist + " Kilometers\n");

}

public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {

double theta = lon1 - lon2;

double dist = Math.sin(degreeToRadian(lat1)) * Math.sin(degreeToRadian(lat2)) + Math.cos(degreeToRadian(lat1)) * Math.cos(degreeToRadian(lat2)) * Math.cos(degreeToRadian(theta));

dist = Math.acos(dist);

dist = radianToDegree(dist);

dist = dist * 60 * 1.1515;

if (unit == 'K') {

dist = dist * 1.609344;

}

return (dist);

}

private static double degreeToRadian(double deg) {

return (deg * Math.PI / 180.0);

}

private static double radianToDegree(double rad) {

return (rad * 180.0 / Math.PI);

}

}

Thanks

We are providing you a code that will prompt the user to enter the latitude and longitude coordinates of the source and destination and accordingly return the distance between them.

import java.util.*;

public class CalculateDistance{

public static void main(String args[]){

System.out.println("Enter the Longitude and Latitude of Source location:");

Scanner input=new Scanner(System.in);

double lat1=input.nextDouble();

double long1=input.nextDouble();

System.out.println("Enter the Longitude and Latitude of destination location:");

double lat2=input.nextDouble();

double long2=input.nextDouble();

CalculateDistance cal=new CalculateDistance();

double dist=cal.distance( lat1, -long1 ,lat2 , -long2, 'K');

System.out.println(dist + " Kilometers\n");

}

public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {

double theta = lon1 - lon2;

double dist = Math.sin(degreeToRadian(lat1)) * Math.sin(degreeToRadian(lat2)) + Math.cos(degreeToRadian(lat1)) * Math.cos(degreeToRadian(lat2)) * Math.cos(degreeToRadian(theta));

dist = Math.acos(dist);

dist = radianToDegree(dist);

dist = dist * 60 * 1.1515;

if (unit == 'K') {

dist = dist * 1.609344;

}

return (dist);

}

private static double degreeToRadian(double deg) {

return (deg * Math.PI / 180.0);

}

private static double radianToDegree(double rad) {

return (rad * 180.0 / Math.PI);

}

}

Thanks

Related Tutorials/Questions & Answers: