Distance Calculation from My Location to Destination Location in Android

Distance calculation from my location to destination location in android

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

How can we calculate distance between current location to lots of destination places in android?

Finally after lots of googling I have done my task.I tried it by Asynchronous Task..
Here is my code..

public View getView(int position, View convertView, ViewGroup Parent) 
{
final ViewHolder holder=new ViewHolder();
View view=convertView;
if (view==null) {
convertView= inflater.inflate(R.layout.layout_row, null);
}

holder.textdistance=(TextView) convertView.findViewById(R.id.textView_Distance);

holder.position = position;

if(data.size()<=0)
{

Toast.makeText(activity, "No data", Toast.LENGTH_LONG).show();
}
else
{
**new ThumbnailTask(position, holder)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);**
}
return convertView;

}
//Thumbnail Class
private static class ThumbnailTask extends AsyncTask {
private int mPosition;
private ViewHolder mHolder;

public ThumbnailTask(int position, ViewHolder holder) {
mPosition = position;
mHolder = holder;
}

/* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
String Distance="3";
String uri="https://maps.googleapis.com/maps/api/distancematrix/json? origins=(Your source Addres like XYZ,South Delhi-110064),&mode=deriving&sensor=false&key=(Your API Key)";

String result= GET(uri);
Log.d("result","res="+result);

try {

//jArray = new JSONObject(result);
JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
JSONArray array = object.getJSONArray("rows");
// Log.d("JSON","array: "+array.toString());

//Routes is a combination of objects and arrays
JSONObject rows = array.getJSONObject(0);
//Log.d("JSON","routes: "+routes.toString());
JSONArray elements = rows.getJSONArray("elements");
// Log.d("JSON","legs: "+legs.toString());

JSONObject steps = elements.getJSONObject(0);
//Log.d("JSON","steps: "+steps.toString());

JSONObject distance = steps.getJSONObject("distance");
Log.d("JSON","distance: "+distance.toString());

Distance = distance.getString("text");
Log.d("final value","tot dis="+Distance);
JSONObject duration=steps.getJSONObject("duration");
// MyDuration=duration.getString("text");

}
catch(JSONException e)
{
Log.d("JSONEXCeption","my exce"+e.getMessage());
}
return Distance;
}

@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
mHolder.textdistance.setText(result.toString());
}

}

//method to execute Url

private static String GET(String url)
{
InputStream inputStream = null;
String result = "";
try {

// create HttpClient
HttpClient httpclient = new DefaultHttpClient();

// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);

// Log.i("Result",result);

else
result = "Did not work!";

} catch (Exception e) {
Log.d("InputStream", "hello"+e);
}

return result;

}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;

inputStream.close();
return result;

}

}

Reference Links are-

http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
https://developers.google.com/maps/documentation/distancematrix/

I am not good in explaining but i am trying my best.Hope it would help to others people like me as i got stuck in this task.

Get path and Distance from my current location to user input location

You can put EditText & Button inside main.xml also. You just need to get the value from EditText so its on your requirement that where you want to put it. For Direction, I have used the following code in my application and it runs fine.

Here,

saddr = source address(lat,lng)

daddr = destination address(lat,lng)

Note that you can also pass Address string in stead of lat/lng.

public void showDirections(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
}

Note that i have used the Web Service of Google Maps to display the Direction.

To calculate distance you have to use the distanceTo method which will return you the distance in double.

double distance = sourceLocation.distanceTo(destinationLocation);

Hope this will help you.

How to calculate distance between two locations using their longitude and latitude value

Here getting distance in miles (mi)

private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}

private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}

Get the distance between two locations in android?

Use the Google Maps Directions API. You'll need to request the directions over HTTP. You can do this directly from Android, or via your own server.

For example, directions from Montreal to Toronto:

GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

You'll end up with some JSON. In routes[].legs[].distance, you'll get an object like this:

     "legs" : [
{
"distance" : {
"text" : "542 km",
"value" : 542389
},

You can also get the polyline information directly from the response object.

Calculating the shortest distance places from my current location and mark the shortest distance places using marker on google map in android

Use the following method to calculate distances

    private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}

private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}


Related Topics



Leave a reply



Submit