distanceBetween() returns inaccurate result?

17,170

Solution 1

To get a distance from a Google Maps I have used Google Directions API and JSON parser to retrieve the distance value:

private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
            StringBuilder stringBuilder = new StringBuilder();
            Double dist = 0.0;
            try {

            destinationAddress = destinationAddress.replaceAll(" ","%20");    
            String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lng1 + "&destination=" + destinationAddress + "&mode=driving&sensor=false";

            HttpPost httppost = new HttpPost(url);

            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            stringBuilder = new StringBuilder();


                response = client.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {

                jsonObject = new JSONObject(stringBuilder.toString());

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

                Log.i("Distance", distance.toString());
                dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return dist;
        }

Solution 2

Google Navigation generally reports driving or walking distance along the set of steps in the directions list, not straight-line distance, which is what distanceBetween() reports.

Share:
17,170
Marcin S.
Author by

Marcin S.

I am an Android Engineer working for United Airlines. I am committed to design and develop mobile applications especially for Android OS. My goal as an Android Engineer is to live up to the same standards that other best developers have set before me. I am always open for new and better opportunities.

Updated on June 08, 2022

Comments

  • Marcin S.
    Marcin S. about 2 years

    I use distanceBetween() of Location class to calculate the distance between two points as follows:

    private float getDistanceInMiles(GeoPoint p1, GeoPoint p2) {
    
        double lat1 = ((double)p1.getLatitudeE6()) / 1e6;
        double lng1 = ((double)p1.getLongitudeE6()) / 1e6;
        double lat2 = ((double)p2.getLatitudeE6()) / 1e6;
        double lng2 = ((double)p2.getLongitudeE6()) / 1e6;
        float [] dist = new float[1];
        Log.i("destination coordinates", "Latitude:" + lat2 + ", Longitude: " + lng2);
            Location.distanceBetween(lat1, lng1, lat2, lng2, dist);
    
        return dist[0] * 0.000621371192f;
    }
    

    Documentation says that distanceBetween() "Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them." However the difference between the result returned by distanceBetween() and real GPS device or Google Navigation app is pretty big. For example my method will return 6.2 miles while google maps shows 10 miles for the same location. I double check the coordinates of the starting point p1 and ending point p2 and they seems to be correct. Is that how distanceBetween() method works or Am I doing something wrong? And by the way Is there a way to use Google Place API to retrieve a distance as a JSON response?

    Distance calculated by Google Maps: 6.1 miles

    enter image description here

    And the result of

    Location.distanceBetween(41.742964, -87.995971, 41.811511, -87.967923, dist) is 
    

    4.947700

  • Marcin S.
    Marcin S. over 11 years
    oh ok. So this is a straight-line distance. How could I retrieve the distance calculated by google app? Google Place Api seems to not include the distance in a JSON response. Thank you for the answer.
  • CommonsWare
    CommonsWare over 11 years
    @MarcinS.: "How could I retrieve the distance calculated by google app?" -- there is no API for that in Android. Whether there is some Google Web service API for it or not, I have no idea.
  • Marcin S.
    Marcin S. over 11 years
    I found something like this developers.google.com/places/documentation/search It's probably unofficial. Thanks.
  • Dan
    Dan over 11 years
    Thanx, I searched for this solution for a while!
  • Jason John
    Jason John almost 10 years
    That's because you're calling this method on the main UI Thread. You must call this method in another Thread or in an AsyncTask
  • Saran
    Saran almost 10 years
    @CommonsWare, just tested the Location.distanceBetween() against LFLL's (r17) calculation and it's 3041m vs. 3032m --> 0.3% difference. The location was accross a city. Both calculations finished in 0 ms.
  • Parth Anjaria
    Parth Anjaria over 6 years
    if we wish to do this offline, then how do we achieve it?