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.
1 2 |
<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
1 2 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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
Reference
https://developer.android.com/training/building-location.html
Please share
Good information bro, keep it up.