Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 27.73 KB | None | 0 0
  1. package com.leavingstone.kazbegi.ui.screens.main
  2.  
  3. import android.Manifest
  4. import android.animation.ValueAnimator
  5. import android.annotation.SuppressLint
  6. import android.app.Activity
  7. import android.content.Intent
  8. import android.graphics.Color
  9. import android.location.Location
  10. import android.os.Build
  11. import android.os.Bundle
  12. import android.os.Looper.getMainLooper
  13. import android.provider.Settings
  14. import androidx.core.content.ContextCompat
  15. import android.text.Editable
  16. import android.text.TextUtils
  17. import android.text.TextWatcher
  18. import android.util.Log
  19. import android.view.LayoutInflater
  20. import android.view.View
  21. import android.view.ViewGroup
  22. import android.view.animation.AccelerateInterpolator
  23. import android.view.animation.AlphaAnimation
  24. import android.view.animation.LinearInterpolator
  25. import android.view.inputmethod.EditorInfo
  26. import android.widget.Toast
  27. import com.leavingstone.kazbegi.R
  28. import com.leavingstone.kazbegi.database.RealmHelper
  29. import com.leavingstone.kazbegi.extensions.hideKeyboard
  30. import com.leavingstone.kazbegi.networking.api.response.GetCategoriesResult
  31. import com.leavingstone.kazbegi.networking.api.response.GetLocationsResult
  32. import com.leavingstone.kazbegi.ui.base.BaseActivity
  33. import com.leavingstone.kazbegi.ui.base.BaseMvpFragment
  34. import com.leavingstone.kazbegi.ui.screens.filterfragment.FilterFragment
  35. import com.leavingstone.kazbegi.ui.screens.general.GeneralDescriptionFragment
  36. import com.leavingstone.kazbegi.ui.screens.menu.MenuFragment
  37. import com.leavingstone.kazbegi.ui.screens.tab.TabFragment
  38. import com.leavingstone.kazbegi.ui.widgets.DoubleClickListener
  39. import com.leavingstone.kazbegi.ui.widgets.adapters.SearchAdapter
  40. import com.leavingstone.kazbegi.utils.FilterHelper
  41. import com.leavingstone.kazbegi.utils.MapViewMarker
  42. import com.leavingstone.kazbegi.view.ext.setDebounceOnClickListener
  43. import com.mapbox.android.core.location.*
  44. import com.mapbox.android.core.permissions.PermissionsManager
  45. //import com.mapbox.android.core.location.LocationEngineListener
  46. //import com.mapbox.android.core.location.LocationEnginePriority
  47. import com.mapbox.api.directions.v5.DirectionsCriteria
  48. import com.mapbox.api.directions.v5.models.DirectionsResponse
  49. import com.mapbox.api.directions.v5.models.DirectionsRoute
  50. import com.mapbox.core.constants.Constants.PRECISION_6
  51. import com.mapbox.geojson.Feature
  52. import com.mapbox.geojson.FeatureCollection
  53. import com.mapbox.geojson.LineString
  54. import com.mapbox.geojson.Point
  55. import com.mapbox.mapboxsdk.Mapbox
  56. import com.mapbox.mapboxsdk.camera.CameraPosition
  57. import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
  58. //import com.mapbox.mapboxsdk.constants.Style
  59. import com.mapbox.mapboxsdk.geometry.LatLng
  60. import com.mapbox.mapboxsdk.geometry.LatLngBounds
  61. import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
  62. import com.mapbox.mapboxsdk.location.modes.CameraMode
  63. import com.mapbox.mapboxsdk.location.modes.RenderMode
  64. import com.mapbox.mapboxsdk.maps.MapboxMap
  65. import com.mapbox.mapboxsdk.maps.Style
  66. //import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerMode
  67. //import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin
  68. import com.mapbox.mapboxsdk.style.layers.LineLayer
  69. import com.mapbox.mapboxsdk.style.layers.PropertyFactory.*
  70. import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
  71. //import com.mapbox.services.android.location.LostLocationEngine
  72. import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute
  73. import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute
  74. //import com.mapbox.services.api.directions.v5.models.DirectionsRoute
  75. import io.realm.Realm
  76. import kotlinx.android.synthetic.main.fragment_main_layout.*
  77. import pub.devrel.easypermissions.AfterPermissionGranted
  78. import pub.devrel.easypermissions.EasyPermissions
  79. import retrofit2.Call
  80. import retrofit2.Callback
  81. import retrofit2.Response
  82. import java.lang.Exception
  83. import kotlin.collections.ArrayList
  84.  
  85.  
  86. /**
  87.  * Created by Giorgi on 12/20/17.
  88.  */
  89. class MainFragment
  90.   : BaseMvpFragment<MainContract.View, MainContract.Presenter>(),
  91.   MainContract.View,
  92.   MapViewMarker.MarkerClickListener,
  93.   EasyPermissions.PermissionCallbacks {
  94.  
  95.   companion object {
  96.  
  97.     const val TAG = "MainFragment"
  98.  
  99.     private val PERMISSIONS = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
  100.     private const val LOCATION_PERMISSION_REQUEST_CODE = 1
  101.  
  102.     private const val FILTER_FRAGMENT_REQUEST_CODE = 100
  103.     private const val GENERAL_FRAGMENT_PATH_REQUEST_CODE = 101
  104.  
  105.     fun newInstance(): MainFragment {
  106.       return MainFragment()
  107.     }
  108.   }
  109.  
  110.   var diractionShow: Boolean = false
  111.   private var mapBoxMap: MapboxMap? = null
  112.  
  113.   private var locationEngine: LocationEngine? = null
  114.  
  115.   //  private var locationPlugin: LocationLayerPlugin? = null
  116.   private var originLocation: Location? = null
  117.  
  118.   private lateinit var originPosition: Point
  119.   private lateinit var destinationPosition: Point
  120.   private var navigationMapRoute: NavigationMapRoute? = null
  121.  
  122.   private var markersList: ArrayList<GetLocationsResult.Params>? = null
  123.   private var filteredLIst: ArrayList<GetLocationsResult.Params>? = null
  124.   private var filtersList: ArrayList<Any>? = null
  125.  
  126.   private var tabFragment: TabFragment? = null
  127.  
  128.   private var cameraBearingAnimator: ValueAnimator? = null
  129.  
  130.   private lateinit var realm: Realm
  131.   private lateinit var realmHelper: RealmHelper
  132.  
  133.   private var afterLanguageChangedAction: ((Unit) -> Unit)? = null
  134.  
  135.   override fun onCreate(savedInstanceState: Bundle?) {
  136.     super.onCreate(savedInstanceState)
  137.  
  138.     realm = Realm.getDefaultInstance()
  139.     realmHelper = RealmHelper(realm)
  140.   }
  141.  
  142.   override fun onCreateView(inflater: LayoutInflater,
  143.                             container: ViewGroup?,
  144.                             savedInstanceState: Bundle?)
  145.     : View? {
  146.     return bind(inflater, R.layout.fragment_main_layout, false)
  147.   }
  148.  
  149.   override fun onViewCreated(view: View,
  150.                              savedInstanceState: Bundle?) {
  151.     super.onViewCreated(view, savedInstanceState)
  152.  
  153.     if (activity?.intent?.hasExtra(BaseActivity.EXTRA_FROM_CHANGE_LANGUAGE) == true) {
  154.       afterLanguageChangedAction = {
  155.         showMenuAfterLanguageChanged()
  156.       }
  157.     }
  158.  
  159.     mapView.onCreate(savedInstanceState)
  160.  
  161.     mapView.getMapAsync {
  162.       onMapReady(it)
  163.     }
  164.  
  165.     presenter.getCategories(realm)
  166.     presenter.getLocationItem(realm)
  167.  
  168.     burger_btn_id.setOnClickListener {
  169.       hideKeyboard()
  170.       val fr = MenuFragment.newInstance()
  171.       fragmentManager?.beginTransaction()
  172.         ?.setCustomAnimations(R.anim.slide_enter, 0, 0, R.anim.slide_exit)
  173.         ?.replace(R.id.root, fr)
  174.         ?.addToBackStack("menu")
  175.         ?.commit()
  176.     }
  177.  
  178.     ic_navigation_btn_id.setOnClickListener(object : DoubleClickListener() {
  179.  
  180.       override fun onSingleClick(v: View) {
  181.         requestLocationPermissions()
  182.       }
  183.  
  184.       override fun onDoubleClick(v: View) {
  185.         val map = mapBoxMap ?: return
  186.  
  187.         val degree = if (map.cameraPosition.bearing.toFloat() > 180) {
  188.           -(360 - map.cameraPosition.bearing.toFloat())
  189.         } else {
  190.           map.cameraPosition.bearing.toFloat()
  191.         }
  192.  
  193.         cameraBearingAnimator?.cancel()
  194.         cameraBearingAnimator = ValueAnimator.ofFloat(degree, 0.toFloat())
  195.  
  196.         val anim = requireNotNull(cameraBearingAnimator)
  197.         anim.interpolator = LinearInterpolator()
  198.         anim.duration = 300L
  199.         anim.addUpdateListener {
  200.           val bearing = it.animatedValue as Float
  201.           map.moveCamera(CameraUpdateFactory
  202.             .newCameraPosition(CameraPosition.Builder()
  203.               .target(LatLng(
  204.                 map.cameraPosition.target.latitude,
  205.                 map.cameraPosition.target.longitude))
  206.               .bearing(bearing.toDouble())
  207.               .build()))
  208.         }
  209.         anim.start()
  210.       }
  211.     })
  212.  
  213.     direction_btn_calear.setOnClickListener {
  214.       navigationMapRoute?.removeRoute()
  215.  
  216.       addMarkers()
  217.  
  218.       direction_btn_container_id.clearAnimation()
  219.       direction_btn_container_id.visibility = View.GONE
  220.       filter_container_id.clearAnimation()
  221.       filter_container_id.visibility = View.VISIBLE
  222.  
  223.       diractionShow = false
  224.     }
  225.  
  226.     direction_btn_container_id.setDebounceOnClickListener {
  227.       updateCamera()
  228.     }
  229.  
  230.     initSearchView()
  231.   }
  232.  
  233.  
  234.   override fun filterListReady(filter: List<GetLocationsResult.Params>) {
  235.     filteredLIst = ArrayList(filter)
  236.     addMarkers()
  237.   }
  238.  
  239.   private fun initSearchView() {
  240.  
  241.     main_search_id.addTextChangedListener(object : TextWatcher {
  242.  
  243.       override fun afterTextChanged(s: Editable?) {
  244.       }
  245.  
  246.       override fun beforeTextChanged(s: CharSequence?,
  247.                                      start: Int,
  248.                                      count: Int,
  249.                                      after: Int) {
  250.       }
  251.  
  252.       override fun onTextChanged(s: CharSequence?,
  253.                                  start: Int,
  254.                                  before: Int,
  255.                                  count: Int) {
  256.         if (count == 0) {
  257.           presenter.searchMarkers("", markersList)
  258.           search_cancel_btn.visibility = View.INVISIBLE
  259.         } else {
  260.           search_cancel_btn.visibility = View.VISIBLE
  261.         }
  262.       }
  263.     })
  264.  
  265.     search_cancel_btn.setOnClickListener {
  266.       main_search_id.text = null
  267.       presenter.searchMarkers("", markersList)
  268.       it.visibility = View.INVISIBLE
  269.     }
  270.  
  271.     main_search_id.setOnEditorActionListener { v, actionId, _ ->
  272.       if (actionId == EditorInfo.IME_ACTION_SEARCH) {
  273.         val term = v.text.toString()
  274.         if (!term.isEmpty()) {
  275.           realmHelper.saveSearchedString(v.text.toString(),
  276.             object : RealmHelper.UpdateSuggestedSearchListener {
  277.               override fun update() {
  278.                 activity?.runOnUiThread {
  279.                   createSearchAdapter()
  280.                 }
  281.               }
  282.             })
  283.         }
  284.         presenter.searchMarkers(v.text, markersList)
  285.         createSearchAdapter()
  286.         hideKeyboard()
  287.       }
  288.       return@setOnEditorActionListener true
  289.     }
  290.  
  291.     createSearchAdapter()
  292.   }
  293.  
  294.   private fun createSearchAdapter() {
  295.     val list = realmHelper.readSearchedString()
  296.     val adapter = SearchAdapter(requireNotNull(context), list, R.layout.search_adapter_item,
  297.       true)
  298.     if (list.isNullOrEmpty()) {
  299.       main_search_id.setAdapter(null)
  300.     } else {
  301.       main_search_id.setAdapter(adapter)
  302.     }
  303.     main_search_id.threshold = 0
  304.   }
  305.  
  306.   private fun removeSearchAdapter() {
  307.     main_search_id.setAdapter(null)
  308.   }
  309.  
  310.   override fun filteredList(filteredLIst: ArrayList<GetLocationsResult.Params>) {
  311.     this.filteredLIst = filteredLIst
  312.     addMarkers()
  313.     tabFragment?.setFilteredList(filteredLIst)
  314.   }
  315.  
  316.   @SuppressLint("MissingPermission")
  317.   private fun requestLocation() {
  318.     if (hasPermission()) {
  319.       initLocationEngine()
  320.       initializeLocationPlugin()
  321.     } else {
  322.       requestLocationPermissions()
  323.     }
  324.   }
  325.  
  326.  
  327.   override fun onMarkerClickListener(idMarker: String) {
  328.     val transaction = fragmentManager?.beginTransaction()
  329.  
  330.     markersList?.let {
  331.       val category = filtersList?.find { it is GetCategoriesResult } as GetCategoriesResult
  332.       val fragment = GeneralDescriptionFragment.newInstance(idMarker, it, category)
  333.       fragment.setTargetFragment(this, GENERAL_FRAGMENT_PATH_REQUEST_CODE)
  334.       transaction?.replace(R.id.tab_fragment_container_id,
  335.         fragment, "tag")?.addToBackStack("stack")?.commit()
  336.       hideBtbAnimation()
  337.       hideKeyboard()
  338.     }
  339.   }
  340.  
  341.   private fun hideBtbAnimation() {
  342.     val alphaAnimation = AlphaAnimation(1f, 0f)
  343.     alphaAnimation.duration = 220
  344.     alphaAnimation.fillAfter = true
  345.     ic_navigation_btn_id.startAnimation(alphaAnimation)
  346.     menu_buton_id.startAnimation(alphaAnimation)
  347.     menu_buton_id.visibility = View.GONE
  348.     filter_container_id.startAnimation(alphaAnimation)
  349.     if (direction_btn_container_id.visibility == View.VISIBLE) {
  350.       direction_btn_container_id.clearAnimation()
  351.       direction_btn_container_id.startAnimation(alphaAnimation)
  352.     }
  353.   }
  354.  
  355.  
  356.   fun showBtbAnimation() {
  357.     val alphaAnimation = AlphaAnimation(0f, 1f)
  358.     alphaAnimation.interpolator = AccelerateInterpolator()
  359.     alphaAnimation.duration = 250
  360.     alphaAnimation.fillAfter = true
  361.     ic_navigation_btn_id.startAnimation(alphaAnimation)
  362.     menu_buton_id.startAnimation(alphaAnimation)
  363.     menu_buton_id.visibility = View.VISIBLE
  364.     filter_container_id.startAnimation(alphaAnimation)
  365.     if (direction_btn_container_id.visibility == View.VISIBLE) {
  366.       direction_btn_container_id.clearAnimation()
  367.       direction_btn_container_id.startAnimation(alphaAnimation)
  368.     }
  369.   }
  370.  
  371.   fun showDirection() {
  372.     if (diractionShow) {
  373.       direction_btn_container_id.clearAnimation()
  374.       direction_btn_container_id.visibility = View.VISIBLE
  375.       filter_container_id.clearAnimation()
  376.       filter_container_id.visibility = View.GONE
  377.     }
  378.   }
  379.  
  380.   override fun loadDataFromBase(params: ArrayList<GetLocationsResult.Params>) {
  381.     this.markersList = params
  382.     addMarkers()
  383.  
  384.     menu_buton_id.setDebounceOnClickListener {
  385.       tabFragment = TabFragment.newInstance(markersList!!)
  386.       val transaction = fragmentManager?.beginTransaction()
  387.       transaction?.setCustomAnimations(R.anim.slide_enter, 0, 0, R.anim.slide_exit)
  388.       transaction?.add(R.id.tab_fragment_container_id, tabFragment!!)?.addToBackStack(null)?.commit()
  389.       hideKeyboard()
  390.       direction_btn_container_id.clearAnimation()
  391.       direction_btn_container_id.visibility = View.GONE
  392.       filter_container_id.clearAnimation()
  393.       filter_container_id.visibility = View.VISIBLE
  394.     }
  395.   }
  396.  
  397.   private fun addMarkers(wayPointFor: GetLocationsResult.Params? = null) {
  398.     val list = filteredLIst?.toList() ?: markersList?.toList() ?: return
  399.     mapBoxMap?.let { map ->
  400.       map.clear()
  401.       MapViewMarker(requireNotNull(context),
  402.         map,
  403.         list,
  404.         wayPointFor,
  405.         this)
  406.     }
  407.   }
  408.  
  409.   @SuppressLint("ResourceType")
  410.   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  411.     super.onActivityResult(requestCode, resultCode, data)
  412. //        filter_container_id.isClickable = true
  413.     if (resultCode == Activity.RESULT_OK) {
  414.       if (requestCode == FILTER_FRAGMENT_REQUEST_CODE) {
  415.         changeFilter()
  416. //                filter_container_id.isClickable = true
  417.       }
  418.       if (requestCode == GENERAL_FRAGMENT_PATH_REQUEST_CODE) {
  419.         data?.let {
  420.           if (checkLocationSwich()) {
  421. //                        requestLocationPermissions()
  422.  
  423.             drawPath(it.extras?.getSerializable("line") as GetLocationsResult.Params)
  424.           } else Toast.makeText(context, resources.getString(R.string.location_warning_text), Toast.LENGTH_SHORT).show()
  425.         }
  426.       }
  427.     }
  428.     if (resultCode == Activity.RESULT_CANCELED) {
  429.       filter_container_id.background = ContextCompat.getDrawable(context!!, R.drawable.non_selected_filter_btn_background)
  430.     }
  431.   }
  432.  
  433.   private fun checkLocationSwich(): Boolean {
  434.     val locationMode: Int
  435.     val locationProviders: String
  436.  
  437.     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  438.       try {
  439.         locationMode = Settings.Secure.getInt(context?.contentResolver, Settings.Secure.LOCATION_MODE)
  440.  
  441.       } catch (e: Settings.SettingNotFoundException) {
  442.         e.printStackTrace()
  443.         return false
  444.       }
  445.       return locationMode != Settings.Secure.LOCATION_MODE_OFF
  446.     } else {
  447.       locationProviders = Settings.Secure.getString(context?.contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
  448.       return !TextUtils.isEmpty(locationProviders)
  449.     }
  450.  
  451.   }
  452.  
  453.   private fun changeFilter() {
  454.     filter_container_id.background = ContextCompat.getDrawable(context!!, R.drawable.filter_bachgraund)
  455.     filter_clear_btn.visibility = View.VISIBLE
  456.     filter_clear_btn.setOnClickListener {
  457.       filter_container_id.background = ContextCompat.getDrawable(context!!, R.drawable.non_selected_filter_btn_background)
  458.       filter_clear_btn.visibility = View.GONE
  459.       FilterHelper.resetFilter()
  460.  
  461.       filteredLIst = null
  462.       addMarkers()
  463.       tabFragment?.setFilteredList(markersList!!)
  464.     }
  465.     presenter.filterMarkers(markersList)
  466.  
  467.   }
  468.  
  469.  
  470.   private fun showDirectionBtn() {
  471.     diractionShow = true
  472.     direction_btn_container_id.clearAnimation()
  473.     direction_btn_container_id.visibility = View.VISIBLE
  474.     filter_container_id.clearAnimation()
  475.     filter_container_id.visibility = View.GONE
  476.   }
  477.  
  478.   private fun hasPermission(): Boolean = EasyPermissions.hasPermissions(
  479.     requireNotNull(context), *PERMISSIONS)
  480.  
  481.   private fun drawPath(params: GetLocationsResult.Params) {
  482.     if (hasPermission()) {
  483.       if (params.coordinates?.coordinatesList?.isNotEmpty() == true) {
  484.         if (params.coordinates?.coordinatesList?.get(0)?.latitude != null &&
  485.           params.coordinates?.coordinatesList?.get(0)?.longitude != null)
  486.           destinationPosition = Point.fromLngLat(params.coordinates?.coordinatesList?.get(0)?.longitude?.toDouble()!!,
  487.             params.coordinates?.coordinatesList?.get(0)?.latitude?.toDouble()!!)
  488.       }
  489.       originLocation?.let {
  490.         originPosition = Point.fromLngLat(it.longitude, it.latitude)
  491.         getRoute(originPosition, destinationPosition, params)
  492.       }
  493.     } else requestLocationPermissions()
  494.   }
  495.  
  496.   private fun getRoute(origin: Point,
  497.                        destination: Point,
  498.                        params: GetLocationsResult.Params) {
  499.     addMarkers(params)
  500.  
  501.     NavigationRoute.builder(context)
  502.       .profile(DirectionsCriteria.PROFILE_WALKING)
  503.       .accessToken(Mapbox.getAccessToken()!!)
  504.       .origin(origin)
  505.       .destination(destination)
  506.       .also { builder ->
  507.         params.coordinates?.coordinatesList
  508.           ?.filter {
  509.             it.longitude != null && it.latitude != null
  510.           }?.onEach {
  511.             builder.addWaypoint(Point.fromLngLat(
  512.               requireNotNull(it.longitude).toDouble(),
  513.               requireNotNull(it.latitude).toDouble()))
  514.           }
  515.       }
  516.       .build().getRoute(object : Callback<DirectionsResponse> {
  517.         override fun onResponse(call: Call<DirectionsResponse>, response: Response<DirectionsResponse>) {
  518.           val res = response.body()
  519.           res?.routes()?.forEach {
  520.             println("---> ${it.routeOptions()?.coordinates()}")
  521.           }
  522.           println()
  523.           if (res == null) {
  524.             Log.e(TAG, "No routes found, make sure you set the right user and access token.")
  525.             return
  526.           } else if (response.body()!!.routes().size < 1) {
  527.             Log.e(TAG, "No routes found")
  528.             return
  529.           }
  530.  
  531.           val currentRoute = response.body()?.routes()?.get(0)
  532.  
  533.           // Draw the route on the map
  534.           if (navigationMapRoute != null) {
  535.             navigationMapRoute!!.removeRoute()
  536.           } else {
  537.             navigationMapRoute = NavigationMapRoute(null, mapView, mapBoxMap!!, R.style.NavigationMapRoute)
  538.           }
  539.           navigationMapRoute!!.addRoute(currentRoute)
  540.  
  541.           updateCamera()
  542.           showDirectionBtn()
  543.         }
  544.  
  545.         override fun onFailure(call: Call<DirectionsResponse>, throwable: Throwable) {
  546.           Log.e(TAG, "Error: " + throwable.message)
  547.         }
  548.       })
  549.   }
  550. //
  551.  
  552.   fun initDottedLineSourceAndLayer(loadedMapStyle: Style) {
  553. //    dashedLineDirectionsFeatureCollection = FeatureCollection.fromFeatures(arrayOf<Feature>());
  554. //    loadedMapStyle.addSource( GeoJsonSource ("SOURCE_ID", dashedLineDirectionsFeatureCollection));
  555.     loadedMapStyle.addLayerBelow(
  556.       LineLayer(
  557.         "DIRECTIONS_LAYER_ID", "SOURCE_ID").withProperties(
  558.         lineWidth(4.5f),
  559.         lineColor(Color.BLACK),
  560.         lineTranslate(arrayOf(0f, 4f)),
  561.         lineDasharray(arrayOf(1.2f, 1.2f))
  562.       ), "road-label-small");
  563.   }
  564.  
  565.   private fun drawNavigationPolylineRoute(route: DirectionsRoute) {
  566.     if (mapBoxMap != null) {
  567.       mapBoxMap?.getStyle { style ->
  568.         val directionsRouteFeatureList = ArrayList<Feature>();
  569.         val lineString = LineString.fromPolyline(route.geometry()!!, PRECISION_6)
  570.         val coordinates = lineString.coordinates()
  571.         coordinates.forEach {
  572.           directionsRouteFeatureList.add(Feature.fromGeometry(LineString.fromLngLats(coordinates)));
  573.         }
  574. //        dashedLineDirectionsFeatureCollection = FeatureCollection.fromFeatures(directionsRouteFeatureList);
  575. //        style.getSourceAs<GeoJsonSource>("SOURCE_ID")?.setGeoJson(dashedLineDirectionsFeatureCollection)
  576.       };
  577.     }
  578.   }
  579.  
  580.   @SuppressLint("MissingPermission")
  581.   @AfterPermissionGranted(LOCATION_PERMISSION_REQUEST_CODE)
  582.   private fun requestLocationPermissions() {
  583.     if (hasPermission()) {
  584.       requestLocation()
  585.       originLocation?.let { setCameraPosition(it) }
  586.     } else {
  587.       EasyPermissions.requestPermissions(this,
  588.         getString(R.string.offline_map),
  589.         LOCATION_PERMISSION_REQUEST_CODE, *PERMISSIONS)
  590.     }
  591.   }
  592.  
  593.  
  594.   override fun onPermissionsDenied(requestCode: Int,
  595.                                    perms: MutableList<String>) {
  596.   }
  597.  
  598.   @SuppressLint("MissingPermission")
  599.   override fun onPermissionsGranted(requestCode: Int,
  600.                                     perms: MutableList<String>) {
  601.     requestLocation()
  602.   }
  603.  
  604.   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
  605.     super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  606.     EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
  607.   }
  608.  
  609.   @SuppressLint("MissingPermission")
  610.   private fun initLocationEngine() {
  611.     locationEngine = LocationEngineProvider.getBestLocationEngine(context!!);
  612.  
  613.     val request = LocationEngineRequest.Builder(1000)
  614.       .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
  615.       .setMaxWaitTime(10000).build();
  616.  
  617.     locationEngine?.requestLocationUpdates(request, locListenerEngine, getMainLooper());
  618.     locationEngine?.getLastLocation(locListenerEngine);
  619.   }
  620.  
  621.   private val locListenerEngine = object :LocationEngineCallback<LocationEngineResult> {
  622.     override fun onSuccess(result: LocationEngineResult?) {
  623.       println("location->>> ${result?.lastLocation}")
  624.     }
  625.  
  626.     override fun onFailure(exception: Exception) {
  627.       exception.printStackTrace()
  628.     }
  629.  
  630.   }
  631.  
  632.   private fun initializeLocationPlugin() {
  633. //    var lp = locationPlugin
  634. //    if (lp == null) {
  635. //      lp = LocationLayerPlugin(mapView, mapBoxMap!!, locationEngine)
  636. //      lp.setLocationLayerEnabled(LocationLayerMode.TRACKING)
  637. //      locationPlugin = lp
  638. //    }
  639.   }
  640.  
  641. //  override fun onLocationChanged(location: Location?) {
  642. //    if (location != null) {
  643. //      originLocation = location
  644. //      locationEngine?.removeLocationEngineListener(this)
  645. //    }
  646. //  }
  647.  
  648.  
  649. //  @SuppressLint("MissingPermission")
  650. //  override fun onConnected() {
  651. //    locationEngine?.requestLocationUpdates()
  652. //  }
  653.  
  654.   private fun showMenuAfterLanguageChanged() {
  655.     val fr = MenuFragment.newInstance()
  656.     fragmentManager?.beginTransaction()
  657.       ?.setCustomAnimations(0, 0, 0, R.anim.slide_exit)
  658.       ?.replace(R.id.root, fr)
  659.       ?.addToBackStack("menu")
  660.       ?.commit()
  661.   }
  662.  
  663.   private fun setCameraPosition(location: Location) {
  664.     mapBoxMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
  665.       LatLng(location.latitude, location.longitude), 13.0))
  666.   }
  667.  
  668.   private fun updateCamera() {
  669.     originLocation?.let {
  670.  
  671.       val latLngBounds = LatLngBounds.Builder()
  672.         .include(LatLng(
  673.           destinationPosition.latitude(),
  674.           destinationPosition.longitude()))
  675.         .include(LatLng(
  676.           it.latitude,
  677.           it.longitude))
  678.         .build()
  679.  
  680.       val padding = requireNotNull(context).resources.getDimension(
  681.         R.dimen.map_camera_bounds_padding).toInt()
  682.       mapBoxMap?.animateCamera(
  683.         CameraUpdateFactory.newLatLngBounds(latLngBounds,
  684.           padding,
  685.           padding,
  686.           padding,
  687.           padding), 1000, null)
  688.     }
  689.   }
  690.  
  691.   private fun onMapReady(map: MapboxMap) {
  692.     mapBoxMap = map
  693.     mapBoxMap?.setStyle(Style.MAPBOX_STREETS) {
  694.       enableLocationComponent()
  695.       initLocationEngine()
  696.     }
  697.     mapBoxMap?.addOnMapClickListener {
  698.       view?.requestFocus()
  699.       hideKeyboard()
  700.       return@addOnMapClickListener true
  701.     }
  702.     addMarkers()
  703.     requestLocation()
  704.   }
  705.  
  706.   @SuppressWarnings("MissingPermission")
  707.   private fun enableLocationComponent() {
  708.  
  709.     // Check if permissions are enabled and if not request
  710.     if (PermissionsManager.areLocationPermissionsGranted(context)) {
  711.  
  712.       // Get an instance of the component
  713.       val locationComponent = mapBoxMap?.locationComponent
  714.  
  715.       // Activate with a built LocationComponentActivationOptions object
  716.       locationComponent?.activateLocationComponent(LocationComponentActivationOptions.builder(context!!, mapBoxMap?.style!!).build())
  717.  
  718.       // Enable to make component visible
  719.       locationComponent?.isLocationComponentEnabled = true
  720.  
  721.       // Set the component's camera mode
  722.       locationComponent?.cameraMode = CameraMode.TRACKING
  723.  
  724.       // Set the component's render mode
  725.       locationComponent?.renderMode = RenderMode.COMPASS
  726.  
  727.  
  728.     } else {
  729.  
  730. //         permissionsManager = PermissionsManager(this)
  731.  
  732. //         permissionsManager?.requestLocationPermissions(this)
  733.  
  734.     }
  735.   }
  736.  
  737.   override fun onLocationItemLoaded(params: ArrayList<GetLocationsResult.Params>) {
  738.     this.markersList = params
  739. //        RealmHelper(realm).saveLocations(params)
  740.     addMarkers()
  741.  
  742.     menu_buton_id.setDebounceOnClickListener {
  743.       tabFragment = TabFragment.newInstance(markersList!!)
  744.       val transaction = fragmentManager?.beginTransaction()
  745.       transaction?.setCustomAnimations(R.anim.slide_enter, 0, R.anim.slide_enter, R.anim.slide_exit)
  746.       transaction?.add(R.id.tab_fragment_container_id, tabFragment!!)?.addToBackStack(null)?.commit()
  747.       hideKeyboard()
  748.       direction_btn_container_id.clearAnimation()
  749.       direction_btn_container_id.visibility = View.GONE
  750.       filter_container_id.clearAnimation()
  751.       filter_container_id.visibility = View.VISIBLE
  752.     }
  753.   }
  754.  
  755.  
  756.   override fun onCategoriesLoad(body: ArrayList<Any>) {
  757.     filtersList = body
  758.     filter_container_id.setDebounceOnClickListener {
  759.       val transaction = fragmentManager?.beginTransaction()
  760.       transaction?.setCustomAnimations(R.anim.slide_up, 0, 0, R.anim.slide_down)
  761.       val fragment = FilterFragment.newInstance(body)
  762.       fragment.setTargetFragment(this@MainFragment, FILTER_FRAGMENT_REQUEST_CODE)
  763.       transaction?.replace(R.id.root, fragment)?.addToBackStack(FilterFragment.newInstance(body).tag)?.commit()
  764.       hideKeyboard()
  765.     }
  766.   }
  767.  
  768.   override val presenter: MainContract.Presenter = MainPresenterImpl()
  769.  
  770.   @SuppressLint("MissingPermission")
  771.   override fun onStart() {
  772.     super.onStart()
  773. //    locationEngine?.requestLocationUpdates()
  774. //    locationPlugin?.onStart()
  775.     mapView.onStart()
  776.   }
  777.  
  778.   override fun onResume() {
  779.     super.onResume()
  780.     mapView.onResume()
  781.  
  782.     val action = afterLanguageChangedAction
  783.     afterLanguageChangedAction = null
  784.     action?.invoke(Unit)
  785.   }
  786.  
  787.   override fun onPause() {
  788.     super.onPause()
  789.     mapView.onPause()
  790.   }
  791.  
  792.   override fun onStop() {
  793.     super.onStop()
  794. //    locationEngine?.removeLocationUpdates()
  795. //    locationPlugin?.onStop()
  796.     mapView.onStop()
  797.   }
  798.  
  799.   override fun onLowMemory() {
  800.     super.onLowMemory()
  801.     mapView.onLowMemory()
  802.   }
  803.  
  804.   override fun onDestroy() {
  805.     super.onDestroy()
  806. //    locationEngine?.deactivate()
  807.     realm.close()
  808.   }
  809.  
  810.   override fun onDestroyView() {
  811.     mapView?.onDestroy()
  812.     super.onDestroyView()
  813.  
  814.   }
  815.  
  816.   override fun onSaveInstanceState(outState: Bundle) {
  817.     super.onSaveInstanceState(outState)
  818.     mapView.onSaveInstanceState(outState)
  819.   }
  820.  
  821.  
  822. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement