Distance Calculator in Android Android by Rajesh Kumar Sahanee - March 24, 2017September 11, 20171 Post Views: 5,604 Hello Friends, Today I am going to share distance calculator code in android which is basically based on GPS. In this code we are going to use GPS location so we need to take below permissions. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 12 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> We need to use below module dependency also compile 'com.google.android.gms:play-services-base:10.0.1' compile 'com.google.android.gms:play-services-location:10.0.1' 12 compile 'com.google.android.gms:play-services-base:10.0.1'compile 'com.google.android.gms:play-services-location:10.0.1' So, Here is the code activity_main.xml activity_main.xml XHTML <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="6dp" android:shrinkColumns="*" android:stretchColumns="*" tools:context="com.zatackcoder.distancecalculator.MainActivity"> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:background="#000" android:gravity="center_horizontal"> <TextView android:id="@+id/msgTV" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:textColor="#fff"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/currentLatLongTV" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Current Location" android:textAlignment="center" android:textSize="24sp" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/startStopB" android:layout_width="match_parent" android:layout_height="60dp" android:text="Start" /> </TableRow> </TableLayout> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 <?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="6dp" android:shrinkColumns="*" android:stretchColumns="*" tools:context="com.zatackcoder.distancecalculator.MainActivity"> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:background="#000" android:gravity="center_horizontal"> <TextView android:id="@+id/msgTV" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:textColor="#fff"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/currentLatLongTV" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Current Location" android:textAlignment="center" android:textSize="24sp" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/startStopB" android:layout_width="match_parent" android:layout_height="60dp" android:text="Start" /> </TableRow> </TableLayout> MainActivity.java MainActivity.java Java package com.zatackcoder.distancecalculator; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleApiClient mGoogleApiClient = null; public static Double startLat = null; public static Double startLong = null; public static Double endLat = null; public static Double endLong = null; TextView msgTV, currentLatLongTV; Button startStopB; boolean started = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeGoogleApi(); msgTV = (TextView)findViewById(R.id.msgTV); currentLatLongTV = (TextView)findViewById(R.id.currentLatLongTV); startStopB = (Button)findViewById(R.id.startStopB); startStopB.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(startStopB.getText().equals("Start")) { started = true; msgTV.setText("Start Walking.."); updateStartLatLong(); startStopB.setText("Stop"); } else if(startStopB.getText().equals("Stop")) { started = false; msgTV.append("\n\nStop Walking.."); updateEndLatLong(); msgTV.append("\n\nDistance from start location is " + getCalculatedDistance() + " Meters\n\n\n"); startStopB.setText("Start"); } } }); } private void initializeGoogleApi() { /*For Location*/ if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } @Override protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override public void onConnected(@Nullable Bundle bundle) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(500); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { startLat = mLastLocation.getLatitude(); startLong = mLastLocation.getLongitude(); currentLatLongTV.setText(startLat + ", " + startLong); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { endLat = location.getLatitude(); endLong = location.getLongitude(); currentLatLongTV.setText(endLat + ", " + endLong); if(started) { currentLatLongTV.append("\nDistance: " + getCalculatedDistance() + " Meters"); } } private void updateStartLatLong() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { startLat = mLastLocation.getLatitude(); startLong = mLastLocation.getLongitude(); msgTV.append("\nStarted From Latitude " + startLat); msgTV.append("\nStarted From Longitude " + startLong); } } private void updateEndLatLong() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { endLat = mLastLocation.getLatitude(); endLong = mLastLocation.getLongitude(); msgTV.append("\nStopped Latitude " + endLat); msgTV.append("\nStopped Longitude " + endLong); } } private Float getCalculatedDistance() { Location startLocation = new Location("Start Location"); startLocation.setLongitude(startLong); startLocation.setLatitude(startLat); Location endLocation = new Location("End Location"); endLocation.setLongitude(endLong); endLocation.setLatitude(endLat); Float distance = Math.abs(startLocation.distanceTo(endLocation)); return distance; } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 package com.zatackcoder.distancecalculator; import android.content.pm.PackageManager;import android.location.Location;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView; import com.google.android.gms.common.ConnectionResult;import com.google.android.gms.common.api.GoogleApiClient;import com.google.android.gms.location.LocationListener;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationServices; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleApiClient mGoogleApiClient = null; public static Double startLat = null; public static Double startLong = null; public static Double endLat = null; public static Double endLong = null; TextView msgTV, currentLatLongTV; Button startStopB; boolean started = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeGoogleApi(); msgTV = (TextView)findViewById(R.id.msgTV); currentLatLongTV = (TextView)findViewById(R.id.currentLatLongTV); startStopB = (Button)findViewById(R.id.startStopB); startStopB.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(startStopB.getText().equals("Start")) { started = true; msgTV.setText("Start Walking.."); updateStartLatLong(); startStopB.setText("Stop"); } else if(startStopB.getText().equals("Stop")) { started = false; msgTV.append("\n\nStop Walking.."); updateEndLatLong(); msgTV.append("\n\nDistance from start location is " + getCalculatedDistance() + " Meters\n\n\n"); startStopB.setText("Start"); } } }); } private void initializeGoogleApi() { /*For Location*/ if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } @Override protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override public void onConnected(@Nullable Bundle bundle) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(500); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { startLat = mLastLocation.getLatitude(); startLong = mLastLocation.getLongitude(); currentLatLongTV.setText(startLat + ", " + startLong); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { endLat = location.getLatitude(); endLong = location.getLongitude(); currentLatLongTV.setText(endLat + ", " + endLong); if(started) { currentLatLongTV.append("\nDistance: " + getCalculatedDistance() + " Meters"); } } private void updateStartLatLong() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { startLat = mLastLocation.getLatitude(); startLong = mLastLocation.getLongitude(); msgTV.append("\nStarted From Latitude " + startLat); msgTV.append("\nStarted From Longitude " + startLong); } } private void updateEndLatLong() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); return; } Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { endLat = mLastLocation.getLatitude(); endLong = mLastLocation.getLongitude(); msgTV.append("\nStopped Latitude " + endLat); msgTV.append("\nStopped Longitude " + endLong); } } private Float getCalculatedDistance() { Location startLocation = new Location("Start Location"); startLocation.setLongitude(startLong); startLocation.setLatitude(startLat); Location endLocation = new Location("End Location"); endLocation.setLongitude(endLong); endLocation.setLatitude(endLat); Float distance = Math.abs(startLocation.distanceTo(endLocation)); return distance; } } AndroidManifest.xml AndroidManifest.xml XHTML <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zatackcoder.distancecalculator"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name="com.zatackcoder.distancecalculator.MainActivity" android:configChanges="orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 123456789101112131415161718192021222324 <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zatackcoder.distancecalculator"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name="com.zatackcoder.distancecalculator.MainActivity" android:configChanges="orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> build.gradle build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.3" defaultConfig { applicationId "com.zatack.distancecalculator" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' compile 'com.google.android.gms:play-services-base:10.0.1' compile 'com.google.android.gms:play-services-location:10.0.1' } 12345678910111213141516171819202122232425262728293031 apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.3" defaultConfig { applicationId "com.zatack.distancecalculator" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }} dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' compile 'com.google.android.gms:play-services-base:10.0.1' compile 'com.google.android.gms:play-services-location:10.0.1'} Screen Shot Download Android Studio Project DistanceCalculator 1 file(s) 25,360.20 KB Download Reference https://developer.android.com/training/building-location.html Please share