Android应用中如何利用LatLng数组计算用户全程行程距离?
Absolutely! Your existing ArrayList<LatLng> points is exactly what you need to compute the total travel distance—no extra data sources required. Here’s a straightforward, efficient way to pull this off:
Core Idea
Total travel distance is just the sum of straight-line (great-circle) distances between every consecutive pair of LatLng points in your list. Android’s LatLng class has a built-in method to handle geographic distance calculations, so you don’t have to mess with complex formulas like Haversine yourself.
Step-by-Step Implementation
Track total distance with a class-level variable
Declare a double variable to keep a running total of the distance traveled:private double totalTravelDistance = 0.0;Calculate distance incrementally (optimized approach)
Instead of recalculating the entire list every time a new point is added, just compute the distance between the latest point and the previous one, then add it to the total. This is far more efficient as your list grows:@Override public void onLocationChanged(Location location) { LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude()); points.add(newPoint); // Only calculate distance if we have at least two points if (points.size() >= 2) { LatLng previousPoint = points.get(points.size() - 2); // distanceTo() returns distance in meters double segmentDistance = newPoint.distanceTo(previousPoint); totalTravelDistance += segmentDistance; } // Your existing polyline drawing code here... }(Optional) Recalculate total distance from the full list
If you ever need to recompute the total from scratch (e.g., after clearing and repopulating the list), use this helper method:private double getTotalDistance(ArrayList<LatLng> points) { double total = 0.0; if (points.size() < 2) return total; for (int i = 1; i < points.size(); i++) { LatLng current = points.get(i); LatLng previous = points.get(i - 1); total += current.distanceTo(previous); } return total; }
Key Notes
- Unit Conversion:
distanceTo()returns distance in meters. To get kilometers, divide the total by 1000; for miles, divide by 1609.34. - Accuracy: This method uses straight-line distance between points, which is an approximation of actual travel distance (it won’t account for turns or detours). For better accuracy, you can filter location updates to only include high-precision fixes (check
location.getAccuracy()). - Edge Cases: Always verify the list has at least 2 points before calculating to avoid index-out-of-bounds errors.
内容的提问来源于stack exchange,提问作者JamesD

