0

I'm looking to use Android's distanceTo() method to calculate the distance between the two different object types. I'm using a LatLng object as it can be added to a marker position on Google Maps.

 LatLng clontarfFC = new LatLng(53.369615, -6.1859571);
 mMap.addMarker(new MarkerOptions().position(clontarfFC).title("Clontarf FC").snippet("St.Annes Park, Clontarf"));

When I add a Location object type into .position() it results in an error as they are incompatible.

I'm declaring a location object like so that will represent the current location of the user of the app.

    Location currentLocation = new Location ("Curent Location");
    currentLocation.setLatitude(53.3419322);
    currentLocation.setLongitude(-6.2670159);

And I'm attempting to find the distance between the two like so:

    final float distance = clontarfFC.distanceTo(currentLocation)/1000;
    final String formattedDistance = String.format("%.02f", distance);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Possible duplicate of https://stackoverflow.com/a/8050255/3505534 – Ramesh sambu Dec 12 '17 at 11:44
  • Thanks for the answer but it is not a duplicate question. That answer covers the distanceTo() method between 2 Location objects as opposed to what I'm trying to measure which is 1 LatLng object and 1 Location object –  Dec 12 '17 at 11:54
  • Try your code by making Longitude value as positive once. – Danger Dec 12 '17 at 11:56
  • If I take out the negative and make the longitude positive the marker moves 500 miles away from where it should be. –  Dec 12 '17 at 12:04

3 Answers3

0

as far as I know there is no built-in method for this, you could however create a simple but thorough converter, like this (where latLng is your LatLng object):

  Location location = new Location("location_name");
  location.setLatitude(latLng .latitude);
  location.setLongitude(latLng .longitude);
  location.setTime(new Date().getTime());

To convert back to LatLng use the following:

  LatLng newLatLng = new LatLng(location.getLatitude(), 
  location.getLongitude());
fuzzKitty
  • 334
  • 3
  • 7
0

add below dependency in your gradle file and

compile 'com.google.maps.android:android-maps-utils:0.4+'

implement below line of code and pass "start LatLng" and "End LatLng" to get the distance between two objects

double distanceBetween = SphericalUtil.computeDistanceBetween(
                    beginLatLng, endLatLng);
Sandeep Kumar
  • 350
  • 4
  • 18
0

as said fuzzKity you can do LatLng position = new LatLng(loc.getLatitude(), loc.getLongitude());

and you can do something like that

float[] results = new float[3];
Location.distanceBetween(coordStart.latitude, coordStart.longitude, position.latitude, position.longitude, results);
double dist = results[0];
Enhakiel
  • 316
  • 2
  • 10