Java: Compute the distance between two points on the surface of earth
Distance Between Two Points
Write a Java program to compute the distance between two points on the earth's surface.
Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2))
Radius of the earth r = 6371.01 Kilometers
Test Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 52.5
Input the longitude of coordinate 2: 35.5
Pictorial Presentation:
Sample Solution:
Java Code:
Explanation:
In the exercise above -
- First, it uses the "Scanner" class to obtain user input.
- The user is prompted to input the latitude and longitude of two coordinates:
- Latitude and longitude of coordinate 1 are read into the variables 'lat1' and 'lon1'.
- Latitude and longitude of coordinate 2 are read into the variables 'lat2' and 'lon2'.
- The code then calls a separate method named "distance_Between_LatLong()" and passes the latitude and longitude values of both coordinates as arguments.
- Inside the "distance_Between_LatLong()" method:
- It converts latitude and longitude values from degrees to radians using the "Math.toRadians()" method to perform trigonometric calculations.
- It calculates the distance between the two coordinates using the Haversine formula for calculating distances on a sphere.
- The calculated distance is returned as a double, representing the distance in kilometers.
- Finally, in the "main() method, the result of the "distance_Between_LatLong()" method is printed, displaying the distance between the two coordinates in kilometers.
Sample Output:
Input the latitude of coordinate 1: 25 Input the longitude of coordinate 1: 35 Input the latitude of coordinate 2: 52.5 Input the longitude of coordinate 2: 35.5 The distance between those points is: 3058.15512920181 km
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to work with miles instead of kilometers.
- Write a program that finds the midpoint between two coordinates.
- Compute the distance between three points instead of two.
- Modify the program to calculate the Manhattan distance.
Go to:
PREV : Polygon Area.
NEXT :
Reverse a String.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.