13

I have to made a project where i need to calculate the distance from my location to destination location and show it in a textview.Here note that this distance updated when my location change.Is it possible to make such type of project ?

[NOTE: without implementing Google map i have to make it.The destination lon ,lat is known.Just have to find my location and make the calculation]

MBMJ
  • 5,323
  • 8
  • 32
  • 51

4 Answers4

16

check the documentation on the google android dev page to see how to listen for position changes. http://developer.android.com/guide/topics/location/obtaining-user-location.html

you can use this function to determine the distance between the current (start) point and the target point.

 /**
 * using WSG84
 * using the Metric system
 */
public static float getDistance(double startLati, double startLongi, double goalLati, double goalLongi){
    float[] resultArray = new float[99];
    Location.distanceBetween(startLati, startLongi, goalLati, goalLongi, resultArray);
    return resultArray[0];
}
CAA
  • 968
  • 10
  • 27
  • 1
    you could start a new asynctask, when a new position is gained (see the link above). In the onpostexecute method you can write the distance in the textview. – CAA May 21 '12 at 10:37
  • 1
    but how?i am sorry .i am new in android.would you please explain it here or give me the code to display it in textview? – MBMJ May 21 '12 at 10:49
  • 2
    you create a listener (see link). in the onLocationChanged() Method you execute a new AsyncTask. This task needs to have a reference on the textview (-> findViewById()). In the doInBackground() Method of the task you calculate the distance and in the onPostExecute() Method you set the text of the textview. Maybe theres a more elegant way to archiv this, but it works :) – CAA May 21 '12 at 12:32
  • Please also divide result with 1000 if you want result in km , like "return resultArray[0]/1000;" – Ramkesh Yadav Jun 12 '20 at 07:11
12

Location.distanceBetween will give to straight distance between two point. If you want distance of PATH between two geographical point then you can use do this by using this class :

public class GetDistance {

public String GetRoutDistane(double startLat, double startLong, double endLat, double endLong)
{
  String Distance = "error";
  String Status = "error";
  try {
      Log.e("Distance Link : ", "http://maps.googleapis.com/maps/api/directions/json?origin="+ startLat +","+ startLong +"&destination="+ endLat +","+ endLong +"&sensor=false");
        JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/directions/json?origin="+ startLat +","+ startLong +"&destination="+ endLat +","+ endLong +"&sensor=false"); 
        Status = jsonObj.getString("status");
        if(Status.equalsIgnoreCase("OK"))
        {
        JSONArray routes = jsonObj.getJSONArray("routes"); 
         JSONObject zero = routes.getJSONObject(0);
         JSONArray legs = zero.getJSONArray("legs");
         JSONObject zero2 = legs.getJSONObject(0);
         JSONObject dist = zero2.getJSONObject("distance");
         Distance = dist.getString("text");
        }
        else
        {
            Distance = "Too Far";
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
return Distance;


} 

}

This will give you distance or length of path/road between two points.

and here is the parser_Json class which parse JSON api

 public class parser_Json {

public static JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    }catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    //try parse the string to a JSON object
    try{
            jArray = new JSONObject(result);
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}

 public static InputStream retrieveStream(String url) {

        DefaultHttpClient client = new DefaultHttpClient(); 

        HttpGet getRequest = new HttpGet(url);

        try {

           HttpResponse getResponse = client.execute(getRequest);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 

              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();
           return getResponseEntity.getContent();

        } 
        catch (IOException e) {
           getRequest.abort();

        }

        return null;

     }

}

Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
4

I have written down 2 different answers here in this Question to calculate difference between two geo-points so not copy pasting here,

Second thing also see this Example the same way you need to implement Locationlistener to get onLocationChanged event.

And in that event calculate difference using above given functions and use them appropriately.

Community
  • 1
  • 1
MKJParekh
  • 34,073
  • 11
  • 87
  • 98
3

This is fairly straightforward using LocationServices to determine your location and updating your TextView with the new distance every time an update is received.

ScouseChris
  • 4,377
  • 32
  • 38