Get the distance between two locations in android?

70,513

Solution 1

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.

Solution 2

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"));

Solution 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

Solution 4

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;
    }
Share:
70,513
Kostya Khuta
Author by

Kostya Khuta

Updated on May 08, 2020

Comments

  • Kostya Khuta
    Kostya Khuta about 4 years

    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.