3

guys i am able to get the current location longitude and Latitude using the below code. I have two buttons Start walking and Stop Walking.

Onclick of Start Walking it will get the current location(longitude and Latitude) the person will start walking from A(source) position and walks from some time and comes back to A(now it becomes destination),after that he clicks on stop walking button.

Now i need to show the user these details:

1.Distance that he walked in Kms.

2.Time he took in minutes.

(optional)3.speed or average speed.

**

Code for getting the current location

**

private EditText editTextShowLocation;
    private Button buttonGetLocation;
    private ProgressBar progress;

    private LocationManager locManager;
    private LocationListener locListener = new MyLocationListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);

        progress = (ProgressBar) findViewById(R.id.progressBar1);
        progress.setVisibility(View.GONE);

        buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
        buttonGetLocation.setOnClickListener(this);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        progress.setVisibility(View.VISIBLE);
        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK", this);
            builder.setNeutralButton("Cancel", this);
            builder.create().show();
            progress.setVisibility(View.GONE);
        }

        if (gps_enabled) {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
        }
        if (network_enabled) {
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                // This needs to stop getting the location data and save the battery power.
                locManager.removeUpdates(locListener); 

                String londitude = "Londitude: " + location.getLongitude();
                String latitude = "Latitude: " + location.getLatitude();
                String altitiude = "Altitiude: " + location.getAltitude();
                String accuracy = "Accuracy: " + location.getAccuracy();
                String time = "Time: " + location.getTime();

                editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
                progress.setVisibility(View.GONE);
            } 
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == DialogInterface.BUTTON_NEUTRAL){
            editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
        }else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

How to acheive this.

Goofy
  • 6,098
  • 17
  • 90
  • 156
  • Similar question:- http://stackoverflow.com/questions/9662320/gps-getting-the-distance-time-while-running-and-walking/9662506#9662506 – Scorpion Mar 12 '12 at 09:40

3 Answers3

8

try this

public class TestActivity extends Activity implements Runnable {
 private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 30000;

    protected LocationManager locationManager;
    static double n=0;
    Long s1,r1;
    double plat,plon,clat,clon,dis;
    MyCount counter;
    Thread t1;
    EditText e1;
    boolean bool=true;

Button b1,b2,b3,b4,b5;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b1=(Button)findViewById(R.id.button1);<--- current position
    b2=(Button)findViewById(R.id.button2);<---- start moving.. calculates distance on clicking this
    b3=(Button)findViewById(R.id.button3);<--- pause
    b4=(Button)findViewById(R.id.button4);<-- resume
    b5=(Button)findViewById(R.id.button5);<-- get distance
    e1=(EditText)findViewById(R.id.editText1);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
});     

}
protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        clat=location.getLatitude();
        clon=location.getLongitude();
        Toast.makeText(TestActivity.this, message,
                Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(TestActivity.this, "null location",
                Toast.LENGTH_LONG).show();
    }

}
public void start (View v){

    switch(v.getId()){

    case R.id.button2:
        t1=new Thread();
        t1.start();
        counter= new MyCount(30000,1000);
     counter.start();
     break;
    case R.id.button3:
        counter.cancel();
        bool=false;
        break;
    case R.id.button4:
        counter= new MyCount(s1,1000);
     counter.start();
     bool=true;
     break;
    case R.id.button5:

        double time=n*30+r1;
        Toast.makeText(TestActivity.this,"distance in metres:"+String.valueOf(dis)+"Velocity in m/sec :"+String.valueOf(dis/time)+"Time :"+String.valueOf(time),Toast.LENGTH_LONG).show();

    }


}


private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );

        Toast.makeText(TestActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(TestActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(TestActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(TestActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}
public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {
        counter= new MyCount(30000,1000);
     counter.start();
     n=n+1;
    }
    @Override
    public void onTick(long millisUntilFinished) {
        s1=millisUntilFinished;
        r1=(30000-s1)/1000;
        e1.setText(String.valueOf(r1));


    }
    }
@Override
public void run() {
    while(bool){
  clat=location.getLatitude();
        clon=location.getLongitude();
        if(clat!=plat || clon!=plon){
            dis+=getDistance(plat,plon,clat,clon);
            plat=clat;
            plon=clon;

        }

    }

}

function for calculating distance...

public double getDistance(double lat1, double lon1, double lat2, double lon2) {
    double latA = Math.toRadians(lat1);
    double lonA = Math.toRadians(lon1);
    double latB = Math.toRadians(lat2);
    double lonB = Math.toRadians(lon2);
    double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
                    (Math.sin(latA) * Math.sin(latB));
    double ang = Math.acos(cosAng);
    double dist = ang *6371;
    return dist;
}

}

5hssba
  • 8,079
  • 2
  • 33
  • 35
  • 1
    can u share the idea of calculating the distance... i mean the logic that using the above code. – Vikky May 14 '13 at 17:28
  • There are many ways to calculate distances. Different ways have different pros and cons (performance vs accuracy). This one is called the Haversine formula: en.wikipedia.org/wiki/Haversine_formula Here are some other formulas: movable-type.co.uk/scripts/latlong.html The haversine formula is concidered accurate. – Joakim Sandqvist May 23 '14 at 06:20
7

First of all. This is more of a ask a question about a problem and then you will receive an answer. People on this board will not do you work for you.

Now to a way to achieve what you want.

You need to use a service in order to keep track of the user and the locations. The easy way would be to incorporate the mytracks service which is available as a addon to your application or use code from mytracks in order to create your own tracking service. http://code.google.com/p/mytracks/

You could check out: http://code.google.com/p/mytracks/w/list

David Olsson
  • 8,085
  • 3
  • 30
  • 38
  • i am sorry for that i tried a lot finding answer for this but couldnt find – Goofy Mar 12 '12 at 09:48
  • hey http://code.google.com/p/mytracks/wiki/MyTracksApi this is what is the code that i need to refer? – Goofy Mar 12 '12 at 09:53
  • You don't need to apologize, but don't create more questions just because someone don't code everything for you. You have been provided several examples and how-tos. And for the MyTracks, check out the wiki. Either use their service and import the library or make your own service. I will NOT do it for you. – David Olsson Mar 12 '12 at 09:55
  • The link you have there says exactly what you need to do in order to use the library. They even give you an example app for the library. So please accept the answer if you want. – David Olsson Mar 12 '12 at 09:57
  • ok ok but i have some questions not on how to implement this but how mytracks will work when a person is walking ?how will it identify that he is walking – Goofy Mar 12 '12 at 10:02
  • It only tracks when a user is moving and tracks the distance, the user can be running, going by car etc. If you want to define speeds etc you probably need to write your own service. So download the mytracks source code and take a look. It is well documented. – David Olsson Mar 12 '12 at 10:08
  • hey i got to know that its for android 4.0 but i am working on android 2.2 – Goofy Mar 12 '12 at 11:59
  • @Goofy you need to use a service in order to track the person when the activity isn't running. Just a FYI. – David Olsson Mar 15 '12 at 11:23
1

You can calculate distance between two geo locations with distanceTo() function
Location destination =new Location("gps");
destination.setLatitude(lat);
destination.setLongitude(lng);
float dist=user_location.distanceTo(destination);

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67
  • 1
    please check this link for more detail http://developer.android.com/reference/android/location/Location.html#distanceTo%28android.location.Location%29 – Jaiprakash Soni Mar 19 '12 at 10:50