33

i need to get distance between two location, but i need to get distance like blue line in the picture. picure

I try next:

public double getDistance(LatLng LatLng1, LatLng LatLng2) {
    double distance = 0;
    Location locationA = new Location("A");
    locationA.setLatitude(LatLng1.latitude);
    locationA.setLongitude(LatLng1.longitude);
    Location locationB = new Location("B");
    locationB.setLatitude(LatLng2.latitude);
    locationB.setLongitude(LatLng2.longitude);
    distance = locationA.distanceTo(locationB);

    return distance;
}

but i get red line distance.

Alberto Bonsanto
  • 17,556
  • 10
  • 64
  • 93
Kostya Khuta
  • 1,846
  • 6
  • 26
  • 48
  • 1
    Hi, You don't need google maps for that use Maths [http://www.movable-type.co.uk/scripts/latlong.html][1] Thanks – Felquir Aug 19 '13 at 09:14
  • 1
    if you want to calculate the distance of route instead of red line than you will have to use google api! which will return you distance and estimated time to cover distance ! – Tarsem Singh Aug 19 '13 at 09:21
  • Its just returns the Calculation for distance of two location....If you want to red line then use Google API. – Piyush Aug 19 '13 at 09:27

9 Answers9

33

Use the Google Maps Directions API. You'll need to request the directions over HTTP. You can do this directly from Android, or via your own server.

For example, directions from Montreal to Toronto:

GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

You'll end up with some JSON. In routes[].legs[].distance, you'll get an object like this:

     "legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           },

You can also get the polyline information directly from the response object.

Chris Broadfoot
  • 5,082
  • 1
  • 29
  • 37
12

As Chris Broadfoot is correct, to parse returned JSON routes[].legs[].distance

"legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           }

Use:

    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray("routes");
    JSONObject routes = routeArray.getJSONObject(0);

    JSONArray newTempARr = routes.getJSONArray("legs");
    JSONObject newDisTimeOb = newTempARr.getJSONObject(0);

    JSONObject distOb = newDisTimeOb.getJSONObject("distance");
    JSONObject timeOb = newDisTimeOb.getJSONObject("duration");

    Log.i("Diatance :", distOb.getString("text"));
    Log.i("Time :", timeOb.getString("text"));
tomrozb
  • 25,773
  • 31
  • 101
  • 122
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
4
public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
    String parsedDistance;
    String response;

    Thread thread=new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
          final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("POST");
          InputStream in = new BufferedInputStream(conn.getInputStream());
          response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

          JSONObject jsonObject = new JSONObject(response);
          JSONArray array = jsonObject.getJSONArray("routes");
          JSONObject routes = array.getJSONObject(0);
          JSONArray legs = routes.getJSONArray("legs");
          JSONObject steps = legs.getJSONObject(0);
          JSONObject distance = steps.getJSONObject("distance");
          parsedDistance=distance.getString("text");
        } catch (ProtocolException e) {
          e.printStackTrace();
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    });

    thread.start();

    try {
      thread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    return parsedDistance;
}
René Hoffmann
  • 2,766
  • 2
  • 20
  • 43
3

Use This:

private String getDistanceOnRoad(double latitude, double longitude,
            double prelatitute, double prelongitude) {
        String result_in_kms = "";
        String url = "http://maps.google.com/maps/api/directions/xml?origin="
                + latitude + "," + longitude + "&destination=" + prelatitute
                + "," + prelongitude + "&sensor=false&units=metric";
        String tag[] = { "text" };
        HttpResponse response = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            response = httpClient.execute(httpPost, localContext);
            InputStream is = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(is);
            if (doc != null) {
                NodeList nl;
                ArrayList args = new ArrayList();
                for (String s : tag) {
                    nl = doc.getElementsByTagName(s);
                    if (nl.getLength() > 0) {
                        Node node = nl.item(nl.getLength() - 1);
                        args.add(node.getTextContent());
                    } else {
                        args.add(" - ");
                    }
                }
                result_in_kms = String.format("%s", args.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result_in_kms;
    }
tomrozb
  • 25,773
  • 31
  • 101
  • 122
Manoj Tarkar
  • 438
  • 4
  • 9
3

You can use following method of Location class in android (if u have lat, longs of both the locations) the method returns approximate distance in meters.

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

Explanation:

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]. Parameters:

startLatitude - the starting latitude

startLongitude the starting longitude

endLatitude the ending latitude

endLongitude the ending longitude

results an array of floats to hold the results

Community
  • 1
  • 1
DevManus
  • 31
  • 2
0

Try this:

private double calculateDistance(double fromLong, double fromLat,
            double toLong, double toLat) {
        double d2r = Math.PI / 180;
        double dLong = (toLong - fromLong) * d2r;
        double dLat = (toLat - fromLat) * d2r;
        double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
                * Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367000 * c;
        return Math.round(d);
    }

Hope this helps.

user2652394
  • 1,686
  • 1
  • 13
  • 15
0

try this code

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
    int Radius = 6371;// radius of earth in Km
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    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.asin(Math.sqrt(a));
    double valueResult = Radius * c;
    double km = valueResult / 1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec = Integer.valueOf(newFormat.format(km));
    double meter = valueResult % 1000;
    int meterInDec = Integer.valueOf(newFormat.format(meter));
    Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
            + " Meter   " + meterInDec);

    return Radius * c;
}
Attaullah
  • 3,856
  • 3
  • 48
  • 63
  • This would return a value from the straight line point of view. I don't think this is what the OP intends. This is an awesome approach regardless ;-) . – Taslim Oseni Jun 26 '19 at 18:13
0

You can use any Distance API. Google API is one of the most popular, but there are also some alternatives, like Distance Matrix API: Documentation

It is very easy to use because you don't need to rewrite code if you were used to using Google Maps API before.

Here is an example of the request:

Get: https://api.distancematrix.ai/distancematrix?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token>

And this is the response example:

{
  "destination_addresses":["Westminster Abbey, Westminster, 
  London SW1P 3PA, UK"],
  "origin_addresses":["Chapel, Fulham, London SW6 1BA, UK"],
  "rows":[
    {
      "elements":[
        {
          "distance":{
            "text": "4.7 miles",
            "value": 7563.898
          },
          "duration":{
            "text": "28 min",
            "value": 1680
          },
          "duration_in_traffic":{
            "text": "28 min",
            "value": 1680
          },
          "status": "OK"
        }
      ]
    }
  ],
  "status": "OK"
}

Disclaimer: I work at a company that creates this API.

-4

To find the distance between 2 locations:

  1. When you first open the app, go to "your timeline" from the drop menu on the top left.

  2. Once the new window opens, choose from the settings on your top right menu and choose "add place".

  3. Add your places and name them like point 1, point 2, or any easy name to remember.

  4. Once your places are added and flagged, go back to the main Window in your Google app.

  5. Click on the blue circle with the arrow in your bottom right.

  6. A new window will open, and you can see on the top there are two text fields in which you can add your "from location" and "distance location".

  7. Click on any text field and type in your saved location in point 3.

  8. Click on the other text field and add your next saved location.

  9. By doing so, Google Maps will calculate the distance between the two locations and show you the blue path on the map.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • The question is about how to find the distance between two points in Android programmatically. This answer is wrong. – Pang May 05 '16 at 04:43