0

I am using the following code the fetching the distance between difference latitude and longitude.Some time it works fine but some time it return the 0.0. I can't understand the reason why it happen. I have enable both GPS and Network
My code is..

 public static String getDistanceOnRoad(String latitude, String longitude,
        String prelatitute, String prelongitude) {
    String result_in_kms = "";
    float num_in_Km=0;
    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));

            //result come with 'm' and 'km' tag so remove this tag
            String  num=stripNonDigits(result_in_kms);

            //if result in KM then does not devide by 1000
            if(!isdisIn_M_or_KM(result_in_kms)){
                 num_in_Km=Float.valueOf(num)/1000;
            }
            else num_in_Km=Float.valueOf(num);
            Log.i("", "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return String.valueOf(num_in_Km);
}
Quy
  • 1

1 Answers1

0

For Finding the distance using GPS, There is no Need of Network Connection. GPS will provide the Latitude and Longitude based on the the time interval you apply.

kindly refer the below link Calculate distance between two latitude-longitude points? (Haversine formula)

Community
  • 1
  • 1
Sugumar
  • 56
  • 3
  • I have used every formula such as haversine, distanceTo(), distanceBetween() but every formula return 0.0 at randomly time. – Quy Sep 25 '15 at 12:15