Beruflich Dokumente
Kultur Dokumente
In this tutorial, we’re building a car location tracking app like Careem and Uber.
Although we’re not developing complete apps like Uber and Careem. But we’ll see how
to online a driver and show the online driver in the passenger app and update the driver
whenever its current location changed.
For online and offline the driver we’re going to use the Firebase Real-time Database.
The driver simply sends its current location to the firebase and passenger see the driver
1 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
PREREQUISITE:
1. You’ve to have a Google Map API key for showing the Map. See this link for
getting the API key.
2. Need a Firebase project for the real-time database. Click to this link for creating a
Firebase project.
Now we’ve Google Map API key and a Firebase project let’s dive into coding and start
2 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
Like I said earlier, there are two apps one for driver and one for the passenger. So, we’re
gonna start making with the driver app.
DRIVERAPP:
First, add the below dependencies to your app level build.gradle file.
1. implementation 'com.google.android.gms:play-services-location:15.0.1'
2. implementation 'com.google.android.gms:play-services-maps:15.0.1'
3. implementation 'com.google.firebase:firebase-database:16.0.1'
After adding the dependencies you need to sync or build your project. Later the
successful build adds the Internet and Location permission to Android. Manifest file.
Now, to show the Google Maps in the app we need to add the meta tags in Android.
Manifest file.
1. <meta-data
2. android:name="com.google.android.gms.version"
3. android:value="@integer/google_play_services_version" />
4.
5. <meta-data
6. android:name="com.google.android.geo.API_KEY"
7. android:value="@string/map_api_key" /> // Change it with your Google Maps API
key.
All the prep work are done for showing the Google Maps and for reading the user current
Location. Now, we need to add the google-services.json file. In this tutorial, I’m not
gonna show you how to create a firebase project, register your Android app to that
firebase project, and add the google-services.json file in Android app. There’s a link
for a video to add the google-services.json file in Android app.
3 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
So, without further ado let’s dive into coding. Below is the UI of the driver app that we’re
gonna make.
You see the UI is very basic, we’ve one SwitchCompat for online and offline the driver
and below is the Google Map itself. Now let’s see the code of the above UI. Below is the
activity_main.xml file.
4 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
24.
25. <android.support.v7.widget.SwitchCompat
26. android:id="@+id/driverStatusSwitch"
27. android:layout_width="wrap_content"
28. android:layout_height="match_parent"
29. android:layout_gravity="end"
30. android:layout_marginEnd="15dp"
31. android:checked="false"
32. android:theme="@style/SCBSwitch" />
33.
34. </FrameLayout>
35.
36. <fragment
37. android:id="@+id/supportMap"
38. android:name="com.google.android.gms.maps.SupportMapFragment"
39. android:layout_width="match_parent"
40. android:layout_height="match_parent"
41. android:layout_below="@+id/driverStatusLayout"
42. tools:context="spartons.com.frisbeeGo.fragments.MapFragment" />
43.
44. </RelativeLayout>
MAINACTIVITY
5 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
LocationServices.getFusedLocationProviderClient(this)
26. locationRequest = uiHelper.getLocationRequest()
27. if (!uiHelper.isPlayServicesAvailable(this)) {
28. Toast.makeText(this, "Play Services did not installed!",
Toast.LENGTH_SHORT).show()
29. finish()
30. } else requestLocationUpdate()
31. val driverStatusTextView = findViewById<TextView>(R.id.driverStatusTextView)
32. findViewById<SwitchCompat>
(R.id.driverStatusSwitch).setOnCheckedChangeListener { _, b ->
33. driverOnlineFlag = b
34. if (driverOnlineFlag) driverStatusTextView.text =
resources.getString(R.string.online_driver)
35. else {
36. driverStatusTextView.text = resources.getString(R.string.offline)
37. firebaseHelper.deleteDriver()
38. }
39. }
40. }
41.
42. @SuppressLint("MissingPermission")
43. private fun requestLocationUpdate() {
44. if (!uiHelper.isHaveLocationPermission(this)) {
45. ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION)
46. return
47. }
48. if (uiHelper.isLocationProviderEnabled(this))
49. uiHelper.showPositiveDialogWithListener(this,
resources.getString(R.string.need_location),
resources.getString(R.string.location_content), object : IPositiveNegativeListener {
50. override fun onPositive() {
51. startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
52. }
53. }, "Turn On", false)
54. locationProviderClient.requestLocationUpdates(locationRequest,
locationCallback, Looper.myLooper())
55. }
56.
57. private fun createLocationCallback() {
58. locationCallback = object : LocationCallback() {
59. override fun onLocationResult(locationResult: LocationResult?) {
60. super.onLocationResult(locationResult)
61. if (locationResult!!.lastLocation == null) return
62. val latLng = LatLng(locationResult.lastLocation.latitude,
locationResult.lastLocation.longitude)
63. Log.e("Location", latLng.latitude.toString() + " , " +
latLng.longitude)
64. if (locationFlag) {
65. locationFlag = false
66. animateCamera(latLng)
67. }
6 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
In MainActivity there are a bunch of important points which I’m going to explain
below.
current location, update the Driver info on Firebase Real-time database if the
driver is online, and animate driver car Marker from the previous Location to a
new one.
7 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
UIHELPER
1. class UiHelper {
2.
3. fun isPlayServicesAvailable(context: Context): Boolean {
4. val googleApiAvailability = GoogleApiAvailability.getInstance()
5. val status = googleApiAvailability.isGooglePlayServicesAvailable(context)
6. return ConnectionResult.SUCCESS == status
7. }
8.
9. fun isHaveLocationPermission(context: Context): Boolean {
10. return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ActivityCompat.checkSelfPermission(context,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context,
android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
11. }
12.
13. fun isLocationProviderEnabled(context: Context): Boolean {
14. val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as
LocationManager
15. return !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
16. }
8 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
17.
18. fun showPositiveDialogWithListener(callingClassContext: Context, title: String,
content: String, positiveNegativeListener: IPositiveNegativeListener, positiveText:
String, cancelable: Boolean) {
19. buildDialog(callingClassContext, title, content)
20. .builder
21. .positiveText(positiveText)
22. .positiveColor(getColor(R.color.colorPrimary, callingClassContext))
23. .onPositive { _, _ -> positiveNegativeListener.onPositive() }
24. .cancelable(cancelable)
25. .show()
26. }
27.
28. private fun buildDialog(callingClassContext: Context, title: String, content:
String): MaterialDialog {
29. return MaterialDialog.Builder(callingClassContext)
30. .title(title)
31. .content(content)
32. .build()
33. }
34.
35.
36. private fun getColor(color: Int, context: Context): Int {
37. return ContextCompat.getColor(context, color)
38. }
39.
40. fun getLocationRequest() : LocationRequest {
41. val locationRequest = LocationRequest.create()
42. locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
43. locationRequest.interval = 3000
44. return locationRequest
45. }
46. }
9 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
the user has not enabled the location provider in mobile settings.
GOOGLEMAPHELPER
1. class GoogleMapHelper {
2.
3. companion object {
4. private const val ZOOM_LEVEL = 18
5. private const val TILT_LEVEL = 25
6. }
7.
8. /**
9. * @param latLng in which position to Zoom the camera.
10. * @return the [CameraUpdate] with Zoom and Tilt level added with the given
position.
11. */
12.
13. fun buildCameraUpdate(latLng: LatLng): CameraUpdate {
14. val cameraPosition = CameraPosition.Builder()
15. .target(latLng)
16. .tilt(TILT_LEVEL.toFloat())
17. .zoom(ZOOM_LEVEL.toFloat())
18. .build()
19. return CameraUpdateFactory.newCameraPosition(cameraPosition)
20. }
21.
22. /**
23. * @param position where to draw the [com.google.android.gms.maps.model.Marker]
24. * @return the [MarkerOptions] with given properties added to it.
25. */
26.
27. fun getDriverMarkerOptions(position: LatLng): MarkerOptions {
28. val options = getMarkerOptions(R.drawable.car_icon, position)
29. options.flat(true)
30. return options
31. }
32.
33. private fun getMarkerOptions(resource: Int, position: LatLng): MarkerOptions {
34. return MarkerOptions()
35. .icon(BitmapDescriptorFactory.fromResource(resource))
36. .position(position)
37. }
38. }
MARKERANIMATIONHELPER
1. class MarkerAnimationHelper {
2.
10 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
The above MarkerAnimationHelper class animate the driver car Marker from the
previous location to user new Location.
LATLNGINTERPOLATOR
1. interface LatLngInterpolator {
2.
3. fun interpolate(fraction: Float, a: LatLng, b: LatLng): LatLng
4.
5. class Spherical : LatLngInterpolator {
6.
7. override fun interpolate(fraction: Float, a: LatLng, b: LatLng): LatLng {
8. // http://en.wikipedia.org/wiki/Slerp
9. val fromLat = toRadians(a.latitude)
10. val fromLng = toRadians(a.longitude)
11. val toLat = toRadians(b.latitude)
12. val toLng = toRadians(b.longitude)
13. val cosFromLat = cos(fromLat)
14. val cosToLat = cos(toLat)
15.
16. // Computes Spherical interpolation coefficients.
11 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
FIREBASEHELPER
12 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
16. .removeValue()
17. }
18.
19. fun updateDriver(driver: Driver) {
20. onlineDriverDatabaseReference
21. .setValue(driver)
22. Log.e("Driver Info", " Updated")
23. }
24.
25. fun deleteDriver() {
26. onlineDriverDatabaseReference
27. .removeValue()
28. }
29. }
Before going to start to explain FirebaseHelper, I want to show you Firebase Real-time
Database Structure.
Diver that’s why I’m setting driverId as a top node and below the is the complete
Driver object. The driverId must be unique because it differs in whole online
13 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
DRIVER
1. data class Driver(val lat: Double, val lng: Double, val driverId: String = "0000")
You can change driverId with the user primary key any anything which is unique.
Alright, guys, this was all from DriverApp. I’m going to end this article here if you want to
see the Passenger app see the next article. If you’ve any queries regarding this post please
do comment below.
Next Part
14 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
AUT HOR
AHSEN SAEED
I’m a mobile product devsigner (i.e. I consider myself as both a developer and a designer) and user
experience/interface engineer. I’m an expert on the Android platform and have been recognized as it by the
community.
15 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
RELATED POSTS
40 COMMENTS
FELIPE R E P LY
2 MONTHS AGO
hello, the database in firebase the values driveId, lat and lng are of type true or double.
FELIPE R E P LY
3 MONTHS AGO
hello, in firebase the database is called online_drivers and 0000 is a table and driverId and lat
and the log are attributes.
my doubt the data that shows the attributes is generated by the app and the user enters that
data.
also to generate the passenger app does not show the car icon.
16 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
AIRENK R E P LY
3 MONTHS AGO
Hello, I have the same problem that CHITGOKS. Everything seems to work fine, but the
Firebase database does not update when I set the “offline” switch of the driver app to “online”.
The database just contains:
appname: null + x
Also, the passenger app does not recognize the position of the driver (and does not detect that
the driver is connected).
FELIPE R E P LY
3 MONTHS AGO
I could run the two applications without problems, but passenger app does not show its
location and the device is activated.
Please help
3 MONTHS AGO
Hey Felipe,
Please check out that the application has the location permission in
settings->apps->Application->Permissions
17 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
CHITGOKS R E P LY
3 MONTHS AGO
hi. your app works ok except for one thing. it does not send data to firebase realtime db
appname: null + x
PREVIOUS
WRITE A COMMENT
18 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
Save my name, email, and website in this browser for the next time I comment.
PO ST COMMEN T
YouTube Instagram
SUBSCRIBE
Subscribe to our newsletters to get an Email on every new Article
Email Address *
19 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
Choose Technology *
SUBS CRIBE
TOP ARTICLES
20 of 21 12/30/2019, 3:43 PM
Car Location Tracking Android App With Firebase Tutorial https://codinginfinite.com/car-location-tracking-android-app-firebase-tuto...
TOP
21 of 21 12/30/2019, 3:43 PM