Reputation: 3348
I am working on a Android Google Map activity Project. I should calculate the traveled distance onLocationchange. Here i am facing a problem when calculatin the distance. Actual point here is to display the distance traveled in the textview when ever the onlocationchange is triggered. Here is the code what i have tried.
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
GeoPoint point = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude() *1E6));
path.add(point);
controller.animateTo(point);
mapview.invalidate();
distance();
}
public void distance(){
start = path.get(0);
stop = path.get(path.size()-1);
double lat1 = start.getLatitudeE6() / 1E6;
double lat2 = stop.getLatitudeE6() / 1E6;
double lon1 = start.getLongitudeE6() / 1E6;
double lon2 = stop.getLongitudeE6() / 1E6;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = c * 6378.1;
d =Double.parseDouble(new DecimalFormat("####.###").format(d));
text.setText(" distance :" + d + "km");
}
And I am passing four locations through DDMS Manual Decimal Here are those locations.
1)lat -122.084095 This is the start point. and the text view is set to 0kms
long 37.422006
2)lat -122.085095 The textview distance is set to 0.088kms
long 37.422006
3)lat -122.085095 The textview distance is set to 0.142kms wroks fine till here
long 37.423006
4)lat -122.084095 The text view distance is set to 0.111kms WTF. now why is that my distance is decreased from 0.142kms to 0.111kms
long 37.423006
5)4)lat -122.084095 The text view distance is set to 0.0kms OMG.. Now the textview shows 0.0kms whats wrong.
long 37.422006
Is this the correct way to calculate distance. What is the mistake i am doing. I think we should for loop for the array of points. But How?? I dont know... PLEASE HELP.THANKS IN ADVANCE
Upvotes: 1
Views: 956
Reputation: 541
The fact that it's saying your distance is 0 when you get back to the original point should set off a lightbulb: What you're actually calculating is the distance from your original point to whatever new point you're emulating, instead of a total distance along the path.
Instead of measuring the distance from point 1 to every other point, you should measure the distance from the last point you were at to the next point and add that to a distance variable you create to hold the total distance.
For example, changing the following should solve your problem:
start = path.get(path.size()-2);
//Be sure to check that there's at least 2 points in your array with an if statement!!
Then later:
totalDistance += d;
textView.setText("Text" + totalDistance);
where totalDistance is some double you define earlier.
Upvotes: 1