How to calculate distance from user's location with another address?

2

What I need to do is pretty simple, but I do not know how.

It works like this: I pass an address to the user and as soon as he is in the place he presses a button, when doing this the application should know if it is in the (or very close) location, if it is, execute a command, if otherwise it informs the user that it is far from the place. How can I do this?

I'm using Android Studio.

    
asked by anonymous 27.09.2015 / 18:34

2 answers

5

You can use Google's own lib for this. Google Maps Android API Utility Library

Add in your Gradle:

dependencies {
    compile 'com.google.maps.android:android-maps-utils:x.y.z'
}

example:

LatLng posicaoInicial = new LatLng(latitude,longitude);
LatLng posicaiFinal = new LatLng(latitude,longitude);

double distance = SphericalUtil.computeDistanceBetween(posicaoInicial, posicaiFinal);
    Log.i("LOG","A Distancia é = "+formatNumber(distance));

private String formatNumber(double distance) {
        String unit = "m";
        if (distance  1000) {
            distance /= 1000;
            unit = "km";
        }

        return String.format("%4.3f%s", distance, unit);
    }

'

    
28.09.2015 / 23:22
3

If you want to know the distance of the route, you can use Google Maps Distance Matrix API .

This API returns, for example, the time and duration between points.

Example: Distance between SP - RJ

Using your coordinates.

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=-23.562984,-46.654261&destinations=-22.951669,-43.210466&key=KEY_CODE

Return:

{
   "destination_addresses" : [ "Christ the Redeemer Statue Rio, Rio de Janeiro - RJ, Brasil" ],
   "origin_addresses" : [
      "Alameda Rio Claro, 313 - Bela Vista, São Paulo - SP, 01332-010, Brasil"
   ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "449 km",
                  "value" : 449025
               },
               "duration" : {
                  "text" : "5 horas 45 minutos",
                  "value" : 20689
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Result: 5h 45min - 449 km

    
23.11.2017 / 19:19