Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.content.Intent
- import android.graphics.BitmapFactory
- import android.os.AsyncTask
- import android.os.Bundle
- import android.view.View
- import android.widget.Toast
- import androidx.appcompat.app.AppCompatActivity
- import androidx.core.content.ContextCompat
- import androidx.drawerlayout.widget.DrawerLayout
- import com.getbase.floatingactionbutton.FloatingActionButton
- import com.google.android.gms.auth.api.signin.GoogleSignInOptions
- import com.mapbox.android.core.permissions.PermissionsListener
- import com.mapbox.android.core.permissions.PermissionsManager
- import com.mapbox.geojson.FeatureCollection
- import com.mapbox.mapboxsdk.Mapbox
- import com.mapbox.mapboxsdk.camera.CameraPosition
- import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
- import com.mapbox.mapboxsdk.geometry.LatLng
- import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
- import com.mapbox.mapboxsdk.location.LocationComponentOptions
- import com.mapbox.mapboxsdk.location.modes.CameraMode
- import com.mapbox.mapboxsdk.location.modes.RenderMode
- import com.mapbox.mapboxsdk.maps.*
- import com.mapbox.mapboxsdk.style.layers.PropertyFactory
- import com.mapbox.mapboxsdk.style.layers.SymbolLayer
- import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
- import java.io.InputStream
- import java.lang.ref.WeakReference
- import java.util.*
- /**
- * Use Kotlin to add a map into a fragment container.
- */
- class HostActivity : AppCompatActivity(), PermissionsListener {
- lateinit var googleSignInClient: GoogleSignInClient
- private lateinit var navController: NavController
- private val mAuth: FirebaseAuth = FirebaseAuth.getInstance()
- private val db: FirebaseFirestore = FirebaseFirestore.getInstance()
- private lateinit var drawerLayout: DrawerLayout
- private lateinit var navViewBinding: DrawerHeaderLayoutBinding
- private val mapView: MapView? = null
- private var permissionsManager: PermissionsManager = PermissionsManager(this)
- private lateinit var mapboxMap: MapboxMap
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setTheme(R.style.AppTheme)
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_basic_kotlin_support_map_frag)
- // Mapbox access token is configured here. This needs to be called either in your application
- // object or in the same activity which contains the mapview.
- Mapbox.getInstance(this, getString(R.string.access_token))
- // Create supportMapFragment
- val mapFragment: SupportMapFragment
- if (savedInstanceState == null) {
- // Create fragment
- val transaction = supportFragmentManager.beginTransaction()
- // Build mapboxMap
- val options = MapboxMapOptions.createFromAttributes(this, null)
- options.camera(CameraPosition.Builder()
- .zoom(9.0)
- .build())
- // Create map fragment
- mapFragment = SupportMapFragment.newInstance(options)
- // Add map fragment to parent container
- transaction.add(R.id.container, mapFragment, "com.mapbox.map")
- transaction.commit()
- } else {
- mapFragment = supportFragmentManager.findFragmentByTag("com.mapbox.map") as SupportMapFragment
- }
- mapFragment.getMapAsync { mapboxMap ->
- this.mapboxMap = mapboxMap
- mapboxMap.setStyle(Style.Builder().fromUri(Style.MAPBOX_STREETS)
- .withImage(ICON_ID, BitmapFactory.decodeResource(
- resources, R.drawable.mapbox_marker_icon_default))
- .withSource(GeoJsonSource(GEOJSON_SOURCE_ID))
- .withLayer(SymbolLayer(LAYER_ID, GEOJSON_SOURCE_ID)
- .withProperties(
- PropertyFactory.iconImage(ICON_ID),
- PropertyFactory.iconAllowOverlap(true),
- PropertyFactory.iconIgnorePlacement(true)
- )
- )) {
- // Map is set up and the style has loaded. Now you can add data or make other map adjustments
- enableLocationComponent(it)
- val toolbar = customToolbar
- setSupportActionBar(toolbar)
- val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
- .requestIdToken(getString(R.string.default_web_client_id))
- .requestEmail()
- .build()
- googleSignInClient = GoogleSignIn.getClient(this, gso)
- drawerLayout = drawer_layout
- navViewBinding = DrawerHeaderLayoutBinding.inflate(layoutInflater, navView, true)
- navController.addOnDestinationChangedListener { _, destination, _ ->
- if (destination.id == R.id.onBoarding ||
- destination.id == R.id.authFragment ||
- destination.id == R.id.loginFragment ||
- destination.id == R.id.signUpFragment
- ) {
- toolbar.visibility = View.GONE
- drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
- } else {
- toolbar.visibility = View.VISIBLE
- drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
- }
- }
- if (!Prefs.getInstance(this)!!.hasCompletedWalkthrough!!) {
- if (mAuth.currentUser == null) {
- graph.startDestination = R.id.authFragment
- } else {
- getUserData()
- graph.startDestination = R.id.homeFragment
- }
- } else {
- graph.startDestination = R.id.onBoarding
- }
- navController.graph = graph
- NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
- navView.setupWithNavController(navController)
- navView.setNavigationItemSelectedListener {
- it.isChecked
- drawerLayout.closeDrawers()
- when (it.itemId) {
- R.id.action_logout -> {
- MyApplication.currentUser!!.active = false
- FirestoreUtil.updateUser(MyApplication.currentUser!!) {
- mAuth.signOut()
- }
- googleSignInClient.signOut()
- MyApplication.currentUser = null
- navController.navigate(R.id.action_logout)
- }
- }
- true
- }
- val fragmentReturnToDeviceLocationButton = findViewById<FloatingActionButton>(R.id.fragmentReturnToDeviceLocationButton)
- fragmentReturnToDeviceLocationButton.setOnClickListener {
- mapboxMap.locationComponent.lastKnownLocation?.let {
- mapboxMap.animateCamera(CameraUpdateFactory
- .newCameraPosition(CameraPosition.Builder()
- .target(LatLng(it.latitude, it.longitude))
- .zoom(15.0)
- .build()), 1000)
- }
- }
- LoadGeoJson(this).execute()
- }
- }
- }
- fun addMarkers(featureCollection: FeatureCollection) {
- mapboxMap.getStyle {
- val geoJsonSource = it.getSourceAs<GeoJsonSource>(GEOJSON_SOURCE_ID)
- geoJsonSource?.let {
- geoJsonSource.setGeoJson(featureCollection)
- }
- }
- }
- private fun enableLocationComponent(loadedMapStyle: Style) {
- // Check if permissions are enabled and if not request
- if (PermissionsManager.areLocationPermissionsGranted(this)) {
- // Create and customize the LocationComponent's options
- val customLocationComponentOptions = LocationComponentOptions.builder(this)
- .trackingGesturesManagement(true)
- .accuracyColor(ContextCompat.getColor(this, R.color.mapboxGreen))
- .build()
- val locationComponentActivationOptions = LocationComponentActivationOptions.builder(this, loadedMapStyle)
- .locationComponentOptions(customLocationComponentOptions)
- .build()
- // Get an instance of the LocationComponent and then adjust its settings
- mapboxMap.locationComponent.apply {
- // Activate the LocationComponent with options
- activateLocationComponent(locationComponentActivationOptions)
- // Enable to make the LocationComponent visible
- isLocationComponentEnabled = true
- // Set the LocationComponent's camera mode
- cameraMode = CameraMode.TRACKING
- // Set the LocationComponent's render mode
- renderMode = RenderMode.COMPASS
- }
- } else {
- permissionsManager = PermissionsManager(this)
- permissionsManager.requestLocationPermissions(this)
- }
- }
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
- permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
- }
- override fun onExplanationNeeded(permissionsToExplain: List<String>) {
- Toast.makeText(this, "This app needs location permissions in order to show its functionality.", Toast.LENGTH_LONG).show()
- }
- override fun onPermissionResult(granted: Boolean) {
- if (granted) {
- enableLocationComponent(mapboxMap.style!!)
- } else {
- Toast.makeText(this, "You didn't grant location permissions", Toast.LENGTH_LONG).show()
- finish()
- }
- }
- private fun getUserData() {
- val ref = db.collection("users").document(mAuth.currentUser!!.uid)
- ref.get().addOnSuccessListener {
- val userInfo = it.toObject(UserModel::class.java)
- navViewBinding.user = userInfo
- MyApplication.currentUser = userInfo
- MyApplication.currentUser!!.active = true
- FirestoreUtil.updateUser(MyApplication.currentUser!!) {
- }
- }.addOnFailureListener {
- val intent = Intent(this, MyApplication::class.java)
- startActivity(intent)
- finish()
- }
- }
- override fun onSupportNavigateUp(): Boolean {
- return NavigationUI.navigateUp(navController, drawerLayout)
- }
- private open class LoadGeoJson internal constructor(activity: HostActivity) : AsyncTask<Void?, Void?, FeatureCollection?>() {
- private val weakReference: WeakReference<HostActivity> = WeakReference(activity)
- override fun doInBackground(vararg params: Void?): FeatureCollection? {
- try {
- val activity = weakReference.get()
- if (activity != null) {
- val inputStream = activity.assets.open("LOCAL_GEOJSON_FILENAME.geojson")
- return FeatureCollection.fromJson(convertStreamToString(inputStream))
- }
- } catch (exception: Exception) {
- }
- return null
- }
- override fun onPostExecute(featureCollection: FeatureCollection?) {
- super.onPostExecute(featureCollection)
- val activity = weakReference.get()
- if (activity != null && featureCollection != null) {
- activity.addMarkers(featureCollection)
- }
- }
- companion object {
- fun convertStreamToString(`is`: InputStream?): String {
- val scanner = Scanner(`is`).useDelimiter("\\A")
- return if (scanner.hasNext()) scanner.next() else ""
- }
- }
- }
- companion object {
- private const val GEOJSON_SOURCE_ID = "GEOJSON_SOURCE_ID"
- private const val ICON_ID = "ICON_ID"
- private const val LAYER_ID = "LAYER_ID"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement