Calculate distance in meters when you know longitude and latitude in java
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Calculating distance between two points, using latitude longitude?
The Java code given by Dommer above gives slightly incorrect results but the small errors add up if you are processing say a GPS track. Here is an implementation of the Haversine method in Java which also takes into account height differences between two points.
/**
* Calculate distance between two points in latitude and longitude taking
* into account height difference. If you are not interested in height
* difference pass 0.0. Uses Haversine method as its base.
*
* lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
* el2 End altitude in meters
* @returns Distance in Meters
*/
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
How to calculate distance between two locations using their longitude and latitude value
Here getting distance in miles (mi)
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
Java: Calculate distance between a large number of locations and performance
this is O(n)
Dont worry about performance. unless every single calculation takes too long (which it isnt).
In java, how can i calculate distance between multiple latitude and longitude?
It is not exact, and Dutch, but I don't think it is hard to understand:
package nl.abz.testjaap;
public class Locatie {
private static final double DOORSNEDE_AARDE = 40000.0;
public final double latitude;
public final double longitude;
public Locatie(double latitude, double longitude) throws IllegalArgumentException {
if (latitude > 90 || latitude < -90) {
throw new IllegalArgumentException("latitude moet tussen - 90 en 90 liggen, was "
+ latitude);
}
if (longitude < -360 || longitude > 360) {
throw new IllegalArgumentException("Longitude moet tussen -360 en 360 liggen was "
+ longitude);
}
this.latitude = latitude;
this.longitude = longitude;
}
/**
* Calculate the distance in KM
*
* @param l2
* @return
*/
public double afstandTot(Locatie l2) {
double lon1 = longitude / 180 * Math.PI;
double lon2 = l2.longitude / 180 * Math.PI;
double lat1 = latitude / 180 * Math.PI;
double lat2 = l2.latitude / 180 * Math.PI;
double x1 = Math.cos(lon1) * Math.cos(lat1);
double y1 = Math.sin(lon1) * Math.cos(lat1);
double z1 = Math.sin(lat1);
double x2 = Math.cos(lon2) * Math.cos(lat2);
double y2 = Math.sin(lon2) * Math.cos(lat2);
double z2 = Math.sin(lat2);
double psi = Math.acos(x1 * x2 + y1 * y2 + z1 * z2);
double afstand = DOORSNEDE_AARDE / (2 * Math.PI) * psi;
return afstand;
}
}
Calculating distance using latitude longitude coordinates in kilometers with Java
You only need to change the last line to:
return new Double((Math.toDegrees(Math.acos(theDistance))) *
69.09*1.6093).intValue();
1 mile = 1.6093 kilometer
How to advance X distance (meters) between two points of latitude and longitude?
So you know latA, lngA, latB, lngB
. From your question, I assume that you know the speed, it's constant, v = 3 m/s. You can get the start time LocalDateTime tA = LocalDateTime.now();
You want to know your coordinates at some moment of time tX
.
In order to do this, I would introduce coefLat
and coefLng
coefficients for transforming coordinates into meters and back. They use mean radius of Earth and translate degrees into radians:
double coefLat = 180 / Math.PI / 6371000;
double coefLng = coefLat / Math.cos(Math.PI * (latA + latB) / 360);
Then calculate distances by Lat and Lng axis and full distance in meters:
double distLat = (latB - latA) / coefLat;
double distLng = (lngB - lngA) / coefLng;
double dist = Math.sqrt(distLat * distLat + distLng * distLng);
double fullTime = dist / v; // Full time needed to pass from A to B in seconds
After some time of moving, find duration and get current coordinates:
LocalDateTime tX = LocalDateTime.now(); // get current time
long dT = Duration.between(tA, tX).getSeconds(); // in seconds
double ratio = dT / fullTime;
double latX = latA + coefLat * ratio * distLat;
double lngX = lngA + coefLng * ratio * distLng;
Please also see this answer
The full code:
public class GetCurrentCoords {
public static void main(String[] args) {
LocalDateTime tA = LocalDateTime.now();
double latA = 51.504870000000004;
double lngA = -0.21533000000000002;
double latB = 51.50475;
double lngB = -0.21571;
double coefLat = 180 / Math.PI / 6371000;
double coefLng = coefLat / Math.cos(Math.PI * (latA + latB) / 360);
double distLat = (latB - latA) / coefLat; // meters
double distLng = (lngB - lngA) / coefLng; // meters
double dist = Math.sqrt(distLat * distLat + distLng * distLng);
System.out.println("distLat = " + distLat + "m; distLng = " + distLng + "m; full dist from A to B = " + dist + "m");
double v = 3;
double fullTime = dist / v; // seconds
System.out.println("full time from A to B = " + fullTime + "s");
// let's move for 4 seconds
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException ex) {
Logger.getLogger(GetCurrentCoords.class.getName()).log(Level.SEVERE, null, ex);
}
LocalDateTime tX = LocalDateTime.now();
long dT = Duration.between(tA, tX).getSeconds();
double ratio = dT / fullTime;
double latX = latA + coefLat * ratio * distLat;
double lngX = lngA + coefLng * ratio * distLng;
System.out.println("Moving " + dT + " seconds; latX = " + latX + "; lngX = " + lngX);
}
}
Calculating new longitude, latitude from old + n meters
The number of kilometers per degree of longitude is approximately
(pi/180) * r_earth * cos(theta*pi/180)
where theta
is the latitude in degrees and r_earth
is approximately 6378 km.
The number of kilometers per degree of latitude is approximately the same at all locations, approx
(pi/180) * r_earth = 111 km / degree
So you can do:
new_latitude = latitude + (dy / r_earth) * (180 / pi);
new_longitude = longitude + (dx / r_earth) * (180 / pi) / cos(latitude * pi/180);
As long as dx
and dy
are small compared to the radius of the earth and you don't get too close to the poles.
Related Topics
How to Show Ellipses on My Textview If It Is Greater Than the 1 Line
How to Send Array of Params Using Volley in Android
== and .Equals() Not Working in Java
Deadobjectexception on Android App
How to Move Firebase Child from One Node to Another in Android
Problems Importing Project into Android Studio Regarding Actionbarsherlock
Android Intent for Sending Email with Attachment
How to Resolve "Duplicate Files Copied in APK Meta-Inf/*"
Divide Elements on Groups in Recyclerview or Grouping Recyclerview Items ,Say by Date
Return Data from Asynctask Class
What Does '->' (Arrow) Mean in Gradle's Dependency Graph
Why Do We Have to Call Super in Android Sometimes
Wrong Version of Keystore on Android Call
Android - Save Image from Url Onto Sd Card
How to Resume Android Activity Programmatically from Background