gpt4 book ai didi

java - 计算 Android/Google map 中行驶的距离

转载 作者:行者123 更新时间:2023-12-01 13:31:33 26 4
gpt4 key购买 nike

我正在开发一个跟踪系统,它涉及跟踪用户路径。我在计算距离时遇到困难。我一直在使用起始位置以及最近的位置更新,但这不会计算实际距离。在 onLocationChanged 方法中,我将位置传递给 updateDistance 函数。我知道路线需要分成几段,然后将每个段的值添加到总数中,但我无法解决问题。

我搜索了该网站,并知道有一些类似的主题,但我还没有找到解决我的问题的方法,因此我将不胜感激任何帮助。这是我计算到目前为止距离的函数。

private void updateDistance(Location location) {
Log.i("updateDistance", "In distance function");
locationA = new Location("point A");
locationB = new Location("point B");

locationA.setLatitude(firstlat);
locationA.setLongitude(firstlon);

lat = location.getLatitude();
lon = location.getLongitude();

locationB.setLatitude(lat);
locationB.setLongitude(lon);
// Calculate the distance between them
distance = locationA.distanceTo(locationB);
// if less than 10 metres, do not record
if (distance < 10.00) {
Log.i("DISTANCE", "Values too close, so not used.");
} else
tv1.setText("Distance Travelled: " + distanceTravelled + " metres");
}

最佳答案

只需保留一个连续的总数即可。不是计算从新位置到第一个纬度、第一个经度位置的距离,而是计算从新位置到前一个位置的距离,并将该距离添加到总距离中。

在 updateDistance 方法所在的类中创建一个成员变量,用于保存先前的位置。最初将其设置为起始位置。还要创建一个成员变量来保存总距离,最初设置为 0。在 updateDistance 方法中,计算给定位置和前一个位置(最初是起始位置)之间的距离,并将其添加到总距离中。然后将当前位置分配给先前的位置变量。

public class YourClass {
private Location prevLocation = startingLocation;
private double distance = 0d;

private void updateDistance(Location location) {
double distanceToLast = location.distanceTo(prevLocation);
// if less than 10 metres, do not record
if (distanceToLast < 10.00) {
Log.i("DISTANCE", "Values too close, so not used.");
} else
distance += distanceToLast;
prevLocation = location;
}
tv1.setText("Distance Travelled: " + distance + " metres");
}
}

关于java - 计算 Android/Google map 中行驶的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21536116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com