3

I need to calculate distance between current location and the destination. I have the latitude and longitude of current and destination locations. I found the below code from SO and internet while searching. But the calculation give 1366 km while the google maps gives 1675 km between 2 locations. Can someone help how can I calculate accurate distance. The destinations are world wide including my current city locations.

//Distance in Kilometers
    fun distanceInKms ( lat1: Double, long1: Double, lat2: Double, long2: Double) : Double
    {
        val degToRad= Math.PI / 180.0;
        val phi1 = lat1 * degToRad;
        val phi2 = lat2 * degToRad;
        val lam1 = long1 * degToRad;
        val lam2 = long2 * degToRad;

        return 6371.01 * Math.acos( Math.sin(phi1) * Math.sin(phi2) + Math.cos(phi1) * Math.cos(phi2) * Math.cos(lam2 - lam1) );
    }

Can someone help me out with this please?

Krishna
  • 343
  • 5
  • 22
User
  • 1,186
  • 4
  • 22
  • 36

2 Answers2

1

Use the android.location.Location class, available since API level 1 in Android. It has a static distanceBetween method doing it all for you.

See: http://developer.android.com/reference/android/location/Location.html

float[] results = new float[1];
android.location.Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
    //distance in meters now in results[0]

Divide by 1000 to get it in kilometers (km).

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
0

you can use it , it get like google don't forgot to add internet permission

      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 + "&mode=driving&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<String> args = new ArrayList<String>();
                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;
    }

this library have class to get time, distance and draw polyline between 2 places it work like google map https://github.com/memo1231014/MUT-master

Example for the library

    RouteInformations rInformation = new RouteInformations(new     AsyncResponse() {

            @Override
            public void processFinish(RouteDetails arg0) {
                // TODO Auto-generated method stub
                try
                {
                  map.addPolyline(arg0.getLineOptions()); //you can add the return line and add it to the map 

                  //here you can get distance , duration it will return like you drive a car 
                  MUT.fastDialog(Map.this,"Time and Distance","Distance : "+arg0.getDistance()+"\nDuration : "+arg0.getDuration());
              }
                catch(Exception e)
                {
                    MUT.lToast(Map.this,"Can't draw line Try Again");
                }
                }
        });

        //you should pass the 2 lat and lang which you want to draw a aline or get distance or duration between them 
         RouteDetails routeDetails=new RouteDetails();
        routeDetails.setLatLong1(from.getPosition());
        routeDetails.setLatLong2(to.getPosition());
        rInformation.execute(routeDetails);
Mohamed Atef
  • 169
  • 3
  • 16