MBMJ
MBMJ

Reputation: 5431

Distance calculation from my location to destination location in android

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]

Upvotes: 13

Views: 21594

Answers (4)

Vipul Purohit
Vipul Purohit

Reputation: 9827

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;

     }

}

Upvotes: 12

MKJParekh
MKJParekh

Reputation: 34301

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.

Upvotes: 4

CAA
CAA

Reputation: 970

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];
}

Upvotes: 16

ScouseChris
ScouseChris

Reputation: 4397

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

Upvotes: 3

Related Questions