Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i calculate the distance between two gps points in Java?

Tags:

I used this code but it doesnt work:

Need the distance between two gps coordinates like 41.1212, 11.2323 in kilometers (Java)

double d2r = (180 / Math.PI); double distance = 0;  try{     double dlong = (endpoint.getLon() - startpoint.getLon()) * d2r;     double dlat = (endpoint.getLat() - startpoint.getLat()) * d2r;     double a =         Math.pow(Math.sin(dlat / 2.0), 2)             + Math.cos(startpoint.getLat() * d2r)             * Math.cos(endpoint.getLat() * d2r)             * Math.pow(Math.sin(dlong / 2.0), 2);     double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));     double d = 6367 * c;      return d;  } catch(Exception e){     e.printStackTrace(); } 
like image 637
Benni Avatar asked Sep 15 '10 07:09

Benni


People also ask

How do you find the distance between GPS coordinates?

For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth.

How do you find the distance from a point to a line in Java?

Computes distance from a point on a plane to line given by two points. double AC = p. distance(endA); double BC = p. distance(endZ); double AB = endA.

How do you find the distance between two XYZ points?

The distance formula states that the distance between two points in xyz-space is the square root of the sum of the squares of the differences between corresponding coordinates. That is, given P1 = (x1,y1,z1) and P2 = (x2,y2,z2), the distance between P1 and P2 is given by d(P1,P2) = (x2 x1)2 + (y2 y1)2 + (z2 z1)2.


2 Answers

Longitude and latitude are given in degrees (0-360). If you want to convert degrees to radians (0-2π) you need to divide by 360 and multiply by 2π, (or equivalently, multiply by π/180). In your code however, you multiply by 180/π.

That is, change

double d2r = (180 / Math.PI); 

into

double d2r = Math.PI / 180; 
like image 95
aioobe Avatar answered Sep 28 '22 08:09

aioobe


have a look a Geocalc

Coordinate lat = new GPSCoordinate(41, .1212); Coordinate lng = new GPSCoordinate(11, .2323); Point point = new Point(lat, lng);  lat = new DegreeCoordinate(51.4613418); lng = new DegreeCoordinate(-0.3035466); Point point2 = new Point(lat, lng); System.out.println("Distance is " + EarthCalc.getDistance(point2, point) / 1000 + " km"); 

Distance is 1448.7325760822912 km

I wrote that library for one my project.

like image 34
Romain Avatar answered Sep 28 '22 09:09

Romain