Classes and variables

Integration of the Google location API requires implementation of GoogleAPIClient, ConnectionCallbacks, and connection failed listeners by MapsActivity. Let us proceed and make the changes to the MapsActivity. Earlier, we had the MapsActivity extend AppCompatActivity and implement the OnMapReadyCallback interface. Now, since we need to use the location API's we have to also implement the GoogleAPIClient, ConnectionCallbacks, and onConnectionFailedListener as shown here:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback ,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

We declare the variables required for GoogleMap and other variables to store the latitude and longitude received from the user and also from the location API:

    private lateinit var mMap: GoogleMap
private var newLat: Double? = null
private var
newLang: Double? = null
private var
chennai: LatLng? = null

private var
AlarmLat: Double? = null
private var
AlarmLong: Double? = null
private var
UserLat: Double? = null
private var
UserLong: Double? = null

//location variables

private val TAG = "MapsActivity"
private lateinit var mGoogleApiClient: GoogleApiClient
private var mLocationManager: LocationManager? = null
lateinit var
mLocation: Location
private var mLocationRequest: LocationRequest? = null

We declare the UPDATE_INTERVAL, the interval in which we would like to receive the updates from the location API, and FASTEST_INTERVAL, the rate at which our app can handle the update. We also declare the LocationManager variable:

     private val UPDATE_INTERVAL = 10000.toLong() // 10 seconds rate at 
// which we would like to receive the updates
private val FASTEST_INTERVAL: Long = 5000 // 5 seconds - rate at
// which app can handle the update
lateinit var locationManager: LocationManager

In the onCreate function, we set the content view for the UI and also ensure the GoogleApiClient is instantiated. We also request that the user enables the location is as follows:

onCreate():

   override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map
is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)


mGoogleApiClient = GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()

mLocationManager =
this.getSystemService(Context.LOCATION_SERVICE) as
LocationManager
checkLocation()
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset