Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package id.agrimart.agriino.activity.area
- import android.app.Activity
- import android.content.Intent
- import android.content.pm.PackageManager
- import android.graphics.Color
- import android.location.Location
- import android.net.Uri
- import android.os.Bundle
- import android.util.Log
- import android.view.LayoutInflater
- import android.view.View
- import android.view.ViewGroup
- import android.widget.Toast
- import androidx.appcompat.app.AppCompatActivity
- import androidx.core.app.ActivityCompat
- import androidx.core.content.ContextCompat
- import androidx.navigation.findNavController
- import androidx.navigation.fragment.findNavController
- import com.google.android.gms.location.FusedLocationProviderClient
- import com.google.android.gms.location.LocationServices
- import com.google.android.gms.maps.CameraUpdateFactory
- import com.google.android.gms.maps.GoogleMap
- import com.google.android.gms.maps.MapView
- import com.google.android.gms.maps.OnMapReadyCallback
- import com.google.android.gms.maps.model.LatLng
- import com.google.android.gms.maps.model.Marker
- import com.google.android.gms.maps.model.MarkerOptions
- import com.google.android.gms.maps.model.Polygon
- import com.google.android.gms.maps.model.PolygonOptions
- import com.google.maps.android.data.kml.KmlLayer
- import id.agrimart.agriino.R
- import id.agrimart.agriino.base.BaseFragment
- import id.agrimart.agriino.config.connection.Resource
- import id.agrimart.agriino.config.endpoint.AreaEndpont
- import id.agrimart.agriino.config.util.Dialog
- import id.agrimart.agriino.databinding.FragmentAreaDetailBinding
- import kotlinx.coroutines.flow.first
- import kotlinx.coroutines.runBlocking
- import org.json.JSONArray
- import org.json.JSONObject
- import java.io.InputStream
- class AreaDetail : BaseFragment<AreaDetailViewModel, FragmentAreaDetailBinding, AreaDetailRepo>(),
- OnMapReadyCallback {
- private lateinit var fusedLocationClient: FusedLocationProviderClient
- private lateinit var mapViews: MapView
- private var currentLocation: LatLng? = null
- private lateinit var googleMap: GoogleMap
- private var polygon: Polygon? = null
- private var listLatLang = mutableListOf<LatLng>()
- private var listMarker = mutableListOf<Marker>()
- private var closedListLatLang = mutableListOf<LatLng>()
- private var latitude = 0.0
- private var longitude = 0.0
- private var marker: Marker? = null
- private val red = 0
- private val green = 0
- private val blue = 0
- override fun onActivityCreated(savedInstanceState: Bundle?) {
- super.onActivityCreated(savedInstanceState)
- with(binding) {
- (activity as AppCompatActivity).setSupportActionBar(topAppBar)
- topAppBar.apply {
- navigationIcon = ContextCompat.getDrawable(context, R.drawable.baseline_arrow_back_24)
- setNavigationOnClickListener {
- findNavController().popBackStack()
- }
- }
- Log.e(TAG, "SAPI >> : ${arguments?.getString("status")}", )
- //mapview
- mapViews = mapView
- mapView.onCreate(savedInstanceState)
- mapView.getMapAsync(this@AreaDetail)
- fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
- if (ActivityCompat.checkSelfPermission(requireContext(),
- android.Manifest.permission.ACCESS_FINE_LOCATION) !=
- PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(requireActivity(),
- arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1)
- } else {
- getLastLocation()
- }
- }
- }
- override fun onMapReady(map: GoogleMap) {
- googleMap = map
- when (arguments?.getString("status")) {
- "B" -> { //new
- Toast.makeText(context, "BARU", Toast.LENGTH_SHORT).show()
- currentLocation?.let { it ->
- val markerOptions = MarkerOptions()
- .position(it)
- .title("You in here")
- googleMap.uiSettings.isZoomControlsEnabled = true
- googleMap.addMarker(markerOptions)
- googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(it, 18.5f))
- latitude = it.latitude
- longitude = it.longitude
- binding.apply {
- fbUploadKml.visibility = View.INVISIBLE
- googleMap.setOnMapClickListener {
- fabClearPoint.visibility = View.VISIBLE
- val markerOpts = MarkerOptions().position(it)
- marker = googleMap.addMarker(markerOpts)
- listLatLang.add(it)
- marker?.let { mk -> listMarker.add(mk) }
- }
- // my location
- fbMylocation.setOnClickListener{
- googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(latitude, longitude), 18.5f))
- }
- // gambar line
- fbDraw.setOnClickListener {
- try {
- if (listLatLang.isNotEmpty()) {
- closedListLatLang = ArrayList(listLatLang)
- closedListLatLang.add(listLatLang[0])
- polygon?.remove()
- val polygonOpts: PolygonOptions = PolygonOptions().addAll(listLatLang).clickable(true)
- polygon = googleMap.addPolygon(polygonOpts)
- polygon!!.strokeColor = Color.rgb(red, green, blue)
- polygon!!.fillColor = Color.BLUE
- } else {
- Toast.makeText(requireContext(), "Maaf gambar dulu", Toast.LENGTH_SHORT).show()
- }
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- // hapus semua line
- fabClearPoint.setOnClickListener {
- for (marker in listMarker) {
- marker.remove()
- }
- listMarker.clear()
- polygon?.remove()
- listLatLang.clear()
- fabClearPoint.visibility = View.INVISIBLE
- }
- btnSimpanBoundary.setOnClickListener {
- getSupportTypeFarm()
- }
- }
- }
- }
- "I" -> { // import KML
- Toast.makeText(context, "IMPORT", Toast.LENGTH_SHORT).show()
- // rt
- binding.apply {
- fbUploadKml.visibility = View.VISIBLE
- fbUploadKml.setOnClickListener {
- val intent = Intent(Intent.ACTION_GET_CONTENT)
- intent.type = "*/*"
- startActivityForResult(intent, KML_FILE_REQUEST_CODE)
- }
- }
- }
- }
- }
- private fun formatLatLngList(list: List<LatLng>): String {
- return list.joinToString(", ") { latLng ->
- "${latLng.longitude} ${latLng.latitude}"
- }
- }
- fun getCountry() {
- viewModel.getCountry()
- viewModel.countryResponse.observe(viewLifecycleOwner) {
- when(it) {
- is Resource.Loading -> {}
- is Resource.Success -> {
- val response = it.value
- // val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, response.streams)
- // binding.atCountry.adapter = adapter
- }
- is Resource.Failure -> {
- val responseBody = it.errorBody
- val jsonErr = JSONObject(responseBody!!.string())
- val msgErr = jsonErr.getString("message")
- context?.let {
- Dialog(it).setDialog("Oops!!", msgErr)
- .setPositiveButton("OKE") { dialog, which ->
- dialog.dismiss()
- }.show()
- }
- }
- }
- }
- }
- fun getSupportTypeFarm() {
- viewModel.getSupportTypeFarm()
- viewModel.supportTypeFarmResponse.observe(viewLifecycleOwner) {
- when(it) {
- is Resource.Loading -> {}
- is Resource.Success -> {
- val response = it.value
- val jsonArray = JSONArray(response.streams.toString())
- for (i in 0 until jsonArray.length()) {
- val jsonObject = jsonArray.getJSONObject(i)
- if (jsonObject.getString("farm_type_code") == "1") {
- val paramInsert = InsertAreaBoundary(
- farm_id = arguments?.getString("farm_id")!!,
- farm_boundary = arguments?.getString("farm_desc")!!,
- country_code = "ID",
- farm_type_code = "0${jsonObject.getString("farm_type_code")}",
- shape = "POLYGON ((${formatLatLngList(closedListLatLang)}))"
- )
- insertBoundaryArea(paramInsert)
- }
- }
- }
- is Resource.Failure -> {
- val responseBody = it.errorBody
- val jsonErr = JSONObject(responseBody!!.string())
- val msgErr = jsonErr.getString("message")
- context?.let {
- Dialog(it).setDialog("Oops!!", msgErr).show()
- }
- }
- }
- }
- }
- private fun insertBoundaryArea(paramInsert: InsertAreaBoundary) {
- viewModel.insertBoundaryFarm(paramInsert)
- viewModel.insertAreaBoundary.observe(viewLifecycleOwner) {
- when(it) {
- is Resource.Loading -> {}
- is Resource.Success -> {
- val response = it.value
- context?.let {
- Dialog(it).setDialog("Insert New Boundary Area", response.message)
- .setPositiveButton("Oke") { dialog, which ->
- findNavController().popBackStack()
- }
- .show()
- }
- }
- is Resource.Failure -> {
- val responseBody = it.errorBody
- val jsonErr = JSONObject(responseBody!!.string())
- val msgErr = jsonErr.getString("message")
- context?.let {
- Dialog(it).setDialog("Oops!!", msgErr).show()
- }
- }
- }
- }
- }
- private fun getLastLocation() {
- if (ActivityCompat.checkSelfPermission(
- requireActivity(),
- android.Manifest.permission.ACCESS_FINE_LOCATION
- ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
- requireActivity(),
- android.Manifest.permission.ACCESS_COARSE_LOCATION
- ) != PackageManager.PERMISSION_GRANTED
- ) {
- // TODO: Consider calling
- // ActivityCompat#requestPermissions
- // here to request the missing permissions, and then overriding
- // public void onRequestPermissionsResult(int requestCode, String[] permissions,
- // int[] grantResults)
- // to handle the case where the user grants the permission. See the documentation
- // for ActivityCompat#requestPermissions for more details.
- return
- }
- fusedLocationClient.lastLocation
- .addOnSuccessListener { location: Location? ->
- if (location != null) {
- currentLocation = LatLng(location.latitude, location.longitude)
- mapViews.getMapAsync(this)
- }
- }
- .addOnFailureListener { e ->
- e.printStackTrace()
- }
- }
- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
- super.onActivityResult(requestCode, resultCode, data)
- if (requestCode == KML_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
- data?.data?.let { uri ->
- println("OPO IKI >> $uri")
- displayKmlOnMap(uri)
- }
- }
- }
- private fun displayKmlOnMap(uri: Uri) {
- try {
- val inputStream: InputStream? = requireActivity().contentResolver.openInputStream(uri)
- Log.e(TAG, "displayKmlOnMap: $inputStream", )
- if (inputStream != null) {
- val kmlLayer = KmlLayer(googleMap, inputStream, requireContext())
- kmlLayer.addLayerToMap()
- }
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults)
- if (requestCode == 1) {
- if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- getLastLocation()
- } else {
- // Handle permission denied
- }
- }
- }
- override fun onResume() {
- super.onResume()
- mapViews.onResume()
- }
- override fun onPause() {
- super.onPause()
- mapViews.onPause()
- }
- override fun onDestroy() {
- super.onDestroy()
- mapViews.onDestroy()
- }
- override fun onLowMemory() {
- super.onLowMemory()
- mapViews.onLowMemory()
- }
- override fun getViewModel() = AreaDetailViewModel::class.java
- override fun getFragmentBinding(
- inflater: LayoutInflater,
- container: ViewGroup?
- ) = FragmentAreaDetailBinding.inflate(layoutInflater, container, false)
- override fun getFragmentRepository(): AreaDetailRepo{
- var token = runBlocking { userPrefrences.tokenFlow.first() }
- val api = clientRemote.buildApi(AreaEndpont::class.java, token)
- return AreaDetailRepo(api)
- }
- companion object {
- private const val TAG = "DETAIL-AREA"
- private val KML_FILE_REQUEST_CODE = 1
- }
- }
Add Comment
Please, Sign In to add comment