How can i calculate the distance between two gps points in Java?
I used this code but it doesnt work:
Need the distan开发者_运维知识库ce 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();
}
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;
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.
The solution from http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter.
Only works if the points are close enough that you can omit that earth is not regular shape.
private double gps2m(float lat_a, float lng_a, float lat_b, float lng_b) { float pk = (float) (180/3.14169); float a1 = lat_a / pk; float a2 = lng_a / pk; float b1 = lat_b / pk; float b2 = lng_b / pk; float t1 = FloatMath.cos(a1)*FloatMath.cos(a2)*FloatMath.cos(b1)*FloatMath.cos(b2); float t2 = FloatMath.cos(a1)*FloatMath.sin(a2)*FloatMath.cos(b1)*FloatMath.sin(b2); float t3 = FloatMath.sin(a1)*FloatMath.sin(b1); double tt = Math.acos(t1 + t2 + t3); return 6366000*tt; } //
see Distance between two GPS coordinates in meter.
Distance between two points (and lots of other useful things) can be found at: http://www.movable-type.co.uk/scripts/latlong.html
http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter shows that double d2r = (180 / Math.PI);
The distance can be calculated with the Esri Geometry library: geodesicDistanceOnWGS84.
I would assume that JTS also has a method for computing distance.
精彩评论