android calculate accurate gps distance. distanceBetween

15,795

you can set your Location Manager like

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
Log.d("GPS Enabled", "GPS Enabled"); 
provider = locationManager.getBestProvider(criteria, true);    
criteria.setAccuracy(Criteria.ACCURACY_FINE);

Now, you can display Latitude and Longitude like this way:

 latitude.setText(String.valueOf(location.getLatitude()));
 longitude.setText(String.valueOf(location.getLongitude())); 

Now, find Distance between two point like below:

float[] results = new float[1];
Location.distanceBetween(
                des_pos.latitude,des_pos.longitude,
                cur_pos.latitude, cur_pos.longitude, results);

            System.out.println("Distance is: " + results[0]);

Try this

Update: Go to this More about Location.distanceBetween(..)

Update2:

You just want to remove updates on your Activity Pause():

    @Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

and, also doing continue into your Activity Resume():

@Override
protected void onResume() {
    super.onResume();
     locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

}
Share:
15,795
Myst
Author by

Myst

Updated on June 28, 2022

Comments

  • Myst
    Myst almost 2 years

    I wanted to calculate the distance the user has walked no matter how little during an activity (such as running) using GPS. Even if GPS is inaccurate, i want a function that can calculate accurate distance.

    In my code below, when I comment out my onLocationChanged code, my app did not crash. but the two TextView and Toast did not display the current location. When I include my onLocationChanged code, my app on my phone crashes a while after. I could not figure out the error.

    Could someone tell me whether or not the way I am using Location.distanceBetween is correct? I felt something is wrong but do not know what.

    updated Java code

    public class MainActivity extends Activity{
        protected LocationManager locationManager;
        EditText userNumberInput;
        EditText userTextInput;
        TextView distanceText;
        TextView latitude;
        TextView longitude;
        double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
        long dist;
        float[] result;
        private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
        private static final long MINIMUM_TIME_BETWEEN_UPDATES = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            distanceText=(TextView)findViewById(R.id.Distance);
            latitude=(TextView)findViewById(R.id.currentLat);
            longitude=(TextView)findViewById(R.id.currentLon);
    
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener); 
            Log.d("GPS Enabled", "GPS Enabled");  
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            String provider = locationManager.getBestProvider(criteria, true);
            Location location=locationManager.getLastKnownLocation(provider);
    
            //Display current location in Toast
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(MainActivity.this, message,
                    Toast.LENGTH_LONG).show();
    
            //Display current location in textview  
            latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude())); 
            longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
            lat1 = location.getLatitude();
            lon1 = location.getLongitude();
            lat3 = 123.0;
            lon3 = 234.0;
            lat4 = 123.0;
            lon4 = 224.0;
            float[] results = new float[1]; 
            Location.distanceBetween(lat3, lon3, lat4, lon4, results);
            System.out.println("Distance is: " + results[0]);
        }
    
        private CharSequence ToString(double latitude2) {
            // TODO Auto-generated method stub
            return null;
        }
    
        LocationListener myLocationListener = new LocationListener() 
        {
            public void onLocationChanged(Location loc2) 
            {
    
            }
        }
    
        public void onProviderDisabled(String provider)
        {
            Toast.makeText(MainActivity.this,
                    "GPS is disabled",
                    Toast.LENGTH_LONG).show();
        }
        public void onProviderEnabled(String provider)
        {
            Toast.makeText(MainActivity.this,
                    "GPS is enabled",
                    Toast.LENGTH_LONG).show();
        }
        public void onStatusChanged(String provider, int status,
                Bundle extras)
        {
            Toast.makeText(MainActivity.this,
                    "GPS status changed",
                    Toast.LENGTH_LONG).show();
        }
    
        };
    
        @Override
        protected void onPause() {
            super.onPause();
            locationManager.removeUpdates(myLocationListener);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener);
    
        }
    }
    

    the LogCat

    01-29 15:37:24.070: I/Process(20836): Sending signal. PID: 20836 SIG: 9
    01-29 15:37:38.305: D/GPS Enabled(24434): GPS Enabled
    01-29 15:37:38.305: D/AndroidRuntime(24434): Shutting down VM
    01-29 15:37:38.305: W/dalvikvm(24434): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
    01-29 15:37:38.305: E/AndroidRuntime(24434): FATAL EXCEPTION: main
    01-29 15:37:38.305: E/AndroidRuntime(24434): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Handler.dispatchMessage(Handler.java:99)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Looper.loop(Looper.java:137)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.main(ActivityThread.java:4898)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invokeNative(Native Method)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invoke(Method.java:511)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at dalvik.system.NativeStart.main(Native Method)
    01-29 15:37:38.305: E/AndroidRuntime(24434): Caused by: java.lang.NullPointerException
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Activity.performCreate(Activity.java:5206)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
    01-29 15:37:38.305: E/AndroidRuntime(24434):    ... 11 more
    01-29 15:38:51.680: D/GPS Enabled(28843): GPS Enabled
    01-29 15:38:51.685: D/AndroidRuntime(28843): Shutting down VM
    01-29 15:38:51.685: W/dalvikvm(28843): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
    01-29 15:38:51.685: E/AndroidRuntime(28843): FATAL EXCEPTION: main
    01-29 15:38:51.685: E/AndroidRuntime(28843): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Handler.dispatchMessage(Handler.java:99)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Looper.loop(Looper.java:137)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.main(ActivityThread.java:4898)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invokeNative(Native Method)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invoke(Method.java:511)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at dalvik.system.NativeStart.main(Native Method)
    01-29 15:38:51.685: E/AndroidRuntime(28843): Caused by: java.lang.NullPointerException
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Activity.performCreate(Activity.java:5206)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
    01-29 15:38:51.685: E/AndroidRuntime(28843):    ... 11 more
    

    i run again but it did not crash or display any output. the log cat is

    01-29 16:22:12.795: D/GPS Enabled(28011): GPS Enabled
    01-29 16:22:12.800: I/System.out(28011): Distance is: 607178.94
    01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.920: D/SensorManager(28011): registerListener :: handle = 0  name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl@41c3a408
    01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    

    whenever i type a letter onto my EditText the logcat keeps increasing by

    01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
    01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67
    01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[2] is 67
    01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
    01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
    01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
    01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67
    

    this type of code. each letter i type the more it increase so i can't paste it all here

  • Myst
    Myst about 10 years
    thanks for helping. it has this "Syntax error on token ")", delete this token"so i add a "(" in after the distanceBetween. then it got "Syntax error on token ",", . expected" at the "des_pos.latitude,des_pos.longitude" the , between. i write it as "Location.distanceBetween((des_pos.latitude,des_pos.longitud‌​e),cur_pos.latitude, cur_pos.longitude, results);" also, just now i tried commenting out onLocatonChanged codes. and just put a toast that says "location has changed" when i run, app did not crash but the toast stay there for a long time
  • M D
    M D about 10 years
    @Myst see my update. r u got distance or not? print into logcat and let me know what happed?
  • Myst
    Myst about 10 years
    i saw that before, but could not fully understand it. thanks for helping so far
  • M D
    M D about 10 years
    @Myst it's very simple you just need to passed current point (lat&lng) and destination point (lat&lng) and one Float result array. that's it
  • M D
    M D about 10 years
    @Myst if my answer is useful to u then +1 up and do not forget to accept
  • Myst
    Myst about 10 years
    i still can't display the distance. nothing cam out. but app did not crash. maybe my phone did not get new location. i testing on my emulator now. but its is loading very long
  • M D
    M D about 10 years
    @Myst please try this into real device or add two static points and get distance between them.
  • Myst
    Myst about 10 years
    i uploaded my logcat when i run on my emulator. just now i have been running on my phone, but since i have to present on emulator like my group, so i test it there. ok, i test using static points first to get the distance. if it works that i try to make it real-time. becuase my app is to calculate distance when a person excercise, i havent implement start button yet.
  • Myst
    Myst about 10 years
    i use this in my oncreate method lat3 = 123.0; lon3 = 234.0; lat4 = 123.0; lon4 = 224.0; float[] results = new float[1]; Location.distanceBetween(lat3, lon3, lat4, lon4, results); System.out.println("Distance is: " + results[0]); there is no result display but app did not crash. i am using my phone
  • M D
    M D about 10 years
    @Myst let me try this. wait
  • Myst
    Myst about 10 years
    i experiencing a wierd problem. when i disable my GPS on my phone, restart it and run the app. the textview and toast still display the same latitude and longitude. if my gps is disabled, where does it get the location from?
  • Myst
    Myst about 10 years
    i not sure whether this is the case but,maybe System.out.println works differently in android? i continue to see if i can spot the errors
  • M D
    M D about 10 years
    @see my new update2 in my answer and also my logcat display distance like:01-29 12:57:24.788: I/System.out(27363): Distance is: 6.8077044E-11
  • Myst
    Myst about 10 years
    i run my app, it crashed..i copy my whole java into above and log cat. what value did you use for MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; and MINIMUM_TIME_BETWEEN_UPDATES = 0;? i uses 0. you uses static lat,lon in the onCreate method too? did i position the onPause onResume correctly? strange why i failed..
  • Myst
    Myst about 10 years
    can your distance display in your phone screen?
  • Myst
    Myst about 10 years
    ok i comment all my on create code. uncomment one by one then run. it did not crash this time. but i did not change any code from the time i crash. it did not display the distance. where does System.out.println display on the screen? and i think it may be might getBestProvider that make it able to get location even with gps disabled?
  • Myst
    Myst about 10 years
    @M D it works. my distance is displayed in log cat screen. now i have to make it accumulate. and display on app screen..thanks for helping me get this far
  • Myst
    Myst about 10 years
    @M D sorry to trouble you, not sure if it is right to ask to do this, but i can improve my code until the last part which i believe to be converting of result[0]/string/double to test whether i can accumulate. stackoverflow.com/questions/21436652/…