[英]Calculate the distance between two positions Android Studio
I'm building an application that tracks my running and walking but I'm getting some trouble with calculating the total distance. 我正在构建一个用于跟踪跑步和行走的应用程序,但是在计算总距离时遇到了一些麻烦。
Here is a part of my code where I'm getting the values of latitude and longitude and where I do my calculation of the distance. 这是我的代码的一部分,在其中我获得了纬度和经度的值,并在其中计算了距离。
public class SportsActicity {
protected Integer userId;
protected ArrayList<Position> route = new ArrayList<Position>();
public SportsActicity() {
this.userId = 1;
}
public void track(Double latitude, Double longitude, Double altitude, float speed, long chron) {
Date currentDate = new Date();
Position currentPosition = new Position(currentDate, latitude, longitude, altitude, speed, chron);
route.add(currentPosition);
// Float velocidade = (locat.getSpeed()*3600)/1000;
}
public double getTotalDistance() {
double distance = 0;
if(route.size() > 1) {
for (Integer i = 0; i < route.size() - 1; i++) {
distance += test(route.get(i).latitude, route.get(i).longitude, route.get(i + 1).latitude, route.get(i + 1).longitude);
}
}
return distance;
}
public Float test(Double lat1, Double lon1, Double lat2, Double lon2) {
double earthRadius = 6371;
double latDiff = Math.toRadians(lat2-lat1);
double lngDiff = Math.toRadians(lon2-lon1);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(lat1))*
Math.cos(Math.toRadians(lat2))* Math.sin(lngDiff /2) *
Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance * meterConversion).floatValue();
}
If I'm not moving, the total distance is always incrementing, around 10 (no idea if it is in meters), and the values I'm getting don't look correct. 如果我不动,总距离总是在增加,大约是10(不知道是否以米为单位),并且我得到的值看起来不正确。
You can use Location's
static method distanceBetween
instead of your whole test
method. 您可以使用
Location's
静态方法distanceBetween
而不是整个test
方法。
int[] results = new int[1];
Location.distanceBetween(lat1, lon1, lat2, lon2, results);
int distance = results[0];
From Google official repository link 从Google官方存储库链接
Usage 用法
double distance = SphericalUtil.computeDistanceBetween(new LatLng(9.000,10.00), new LatLng(9.000,11.00));
The above method will returns the distance between two LatLngs, in meters. 上面的方法将返回两个LatLng之间的距离(以米为单位)。 Or try this
或者试试这个
private String getDistance(LatLng my_latlong,LatLng frnd_latlong){
Location l1=new Location("One");
l1.setLatitude(my_latlong.latitude);
l1.setLongitude(my_latlong.longitude);
Location l2=new Location("Two");
l2.setLatitude(frnd_latlong.latitude);
l2.setLongitude(frnd_latlong.longitude);
float distance=l1.distanceTo(l2);
String dist=distance+" M";
if(distance>1000.0f)
{
distance=distance/1000.0f;
dist=distance+" KM";
}
return dist;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.