Edit: It was suggested that I use this formula to calculate the distance between my current location and a marker that is placed, but I am getting the same result no matter where I place the marker, which is 1.004822115417686E7
. I will show that method in my updated code.
I just want the distance from my location to the Marker that is placed. I tried to use the distanceTo(Location dest)
method, but I do not know how to convert my Marker LatLng into a Location object, if that's even possible. As a result, I decided to go with the Location.distanceBetween
method.
The problem is that my results are not correct at all. What am I doing wrong? Have I misread the Android Docs?
All I'm doing is performing an onMapLongClick
to add a Marker. There is not a Marker on the current location. It will just be the blue dot to show where the user is located.
The basics of map usage:
User parks car. User places marker on map where they parked. User goes and does something in a nearby building. User comes back out, opens app, locates car. App will show distance to car. Distances do not need to account for obstacles, turns, etc. Just a straight line distance will work.
Code:
@Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
//m is the Marker
m = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
float[] results = new float[1];
Location currentPos = new Location(LocationManager.GPS_PROVIDER);
latLng = m.getPosition();
Location.distanceBetween(currentPos.getLatitude(), currentPos.getLongitude(), latLng.latitude, latLng.longitude, results);
Log.d(TAG, "Distance using distanceBetween(): " + results[0] + " meters");
Log.d(TAG, "Distance using meterDistanceBetweenPoints: " + meterDistanceBetweenPoints((float)currentPos.getLatitude(), (float)currentPos.getLongitude(), (float)latLng.latitude, (float)latLng.longitude));
Toast.makeText(getApplicationContext(), "Marker Added", Toast.LENGTH_SHORT).show();
}
private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
float pk = (float) (180.f/Math.PI);
float a1 = lat_a / pk;
float a2 = lng_a / pk;
float b1 = lat_b / pk;
float b2 = lng_b / pk;
double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
double t3 = Math.sin(a1) * Math.sin(b1);
double tt = Math.acos(t1 + t2 + t3);
return 6366000 * tt;
}
This is the output in Logcat:
Distance using distanceBetween(): 1.0061643E7 meters
Distance using meterDistanceBetweenPoints: 1.004822115417686E7
What am I doing wrong here? According to the Android Docs, it says:
The computed distance is stored in results[0]
I'm literally placing a Marker 20-30 feet from my location, so what is this strange output? It's not even correct for the new function I attempted.