114k views
0 votes
Write a program to calculate the great circle distance between two points on the surface of a sphere. If p1(x1, y1) and p2(x2,y2) are geographic latitude and longitude of two points, the great circle distance can be computed as

1 Answer

2 votes

Answer:

import java.lang.*;

public class distance { public static double distance(double latitude1,

double latitude2, double longitude1,

double longitude2)

{

// Convert Latitude and Longitude to Radians

longitude1 = Math.toRadians(longitude1);

longitude2 = Math.toRadians(longitude2);

latitude1 = Math.toRadians(latitude1);

latitude2 = Math.toRadians(latitude2);

double d_longitude = longitude2 - longitude1;

double d_latitude = latitude2 - latitude1;

double a = Math.pow(Math.sin(d_latitude / 2), 2)

+ Math.cos(latitude1) * Math.cos(latitude2)

* Math.pow(Math.sin(d_longitude / 2),2);

double val = 2 * Math.asin(Math.sqrt(a));

// Radius of earth in kilometers is 6371

double earth_radius = 6371;

// Calculate and return the distance

return(val * earth_radius);

}

// Main Method

public static void main(String[] args)

{

double latitude1 = 67.32055555555556;

double latitude2 = 83.31861111111111;

double longitude1 = -1.7217899;

double longitude2 = -1.6567799;

System.out.println(distance(latitude1, latitude2,

longitude1, longitude2) + " K.M");

}

}

Step-by-step explanation:

This program is implemented in Java programming language

The formula for the shortest distance between two points on the earth is:

Distance = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 – long1)]

The latitude and longitude of the two points must be known

The latitude and longitude are converted into radians using built in methods in java.

Take value for the radius of the earth in Kilometers 6371;

Note that a seperate method has been created to calculate the distance

In the driver method (main), values for latitude and logitudes for both places have been hard-corded, then the method distance is called and passed those values

Note also that the distance has been calculated in Kilometers

User Haniku
by
6.1k points