Я использую fusedlocationclient для получения текущего местоположения пользователя, но как-то lasLocation имеет значение null. Я пытался заставить это работать в течение нескольких дней. Буду очень признателен, если кто-нибудь сможет мне помочь.
Вот мой фрагмент местоположения:
package com.example.atry.MakeComplaint
import Retrofit.INodeJS
import Retrofit.Observables
import Retrofit.RetrofitClient
import android.app.Activity
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Context.*
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.*
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.MapView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import com.ashiqur.weatherapp.utils.GPSUtils
import com.example.atry.R
import com.google.android.gms.common.GooglePlayServicesNotAvailableException
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.dynamic.SupportFragmentWrapper
import com.google.android.gms.location.*
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.*
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.fragment_complaint_details.view.*
import kotlinx.android.synthetic.main.fragment_location.*
import kotlinx.android.synthetic.main.fragment_location.view.*
import retrofit2.Call
import retrofit2.Response
import java.io.IOException
import java.util.Observer
import java.util.Optional.empty
import java.util.jar.Manifest
import javax.security.auth.callback.Callback
class LocationFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
override fun onMarkerClick(p0: Marker?)= false
private lateinit var map: GoogleMap
private lateinit var mapView : MapView
lateinit var myAPI: INodeJS
var MyCategory: Observables.ComplaintType?=null
private var listener: OnLocationFragmentInteractionListener? = null
var objectComplaint =
Observables.Complaint(
1 , "dummy problem" ,
"url" ,
Observables.Location("99","99"),
Observables.ComplaintType("Smell", "null"),
Observables.Status(2 , "Unresolved")
)
//for updating user's location/ for current location
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
private lateinit var lastLocation: Location
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val permissions = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION)
requestPermissions( permissions,0)
getLocationUpdates()
//INIT API
val retrofit = RetrofitClient.instanc
myAPI = retrofit.create(INodeJS::class.java)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(com.example.atry.R.layout.fragment_location, container, false)
mapView = v.findViewById(R.id.maps)
mapView.onCreate(savedInstanceState)
mapView.onResume()
try {
MapsInitializer.initialize(getActivity()!!.getApplicationContext());
} catch (sendEx: IntentSender.SendIntentException) {
sendEx.printStackTrace();
}
mapView.getMapAsync(this)
v.backToList.setOnClickListener {
backFragment()
}
v.forwardToDescription.setOnClickListener{
getAllData()
}
return v
}
/**
* call this method in onCreate
* onLocationResult call when location is changed
*/
private fun getLocationUpdates() {
//with fusedLocationClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
locationRequest = LocationRequest()
locationRequest.interval = 1000
locationRequest.fastestInterval = 5000
locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
if (locationResult.locations.isNotEmpty()) {
// get latest location
lastLocation = locationResult.lastLocation
Log.d("lastlocation",lastLocation.toString())
// use your location object
// get latitude , longitude and other info from this
}
}
}
}
//Places the marker on the map and changes its style.
//start location updates
private fun startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
null /* Looper */
)
}
// stop location updates
private fun stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback)
}
// start receiving location update when activity visible/foreground
override fun onResume() {
super.onResume()
mapView.onResume()
startLocationUpdates()
}
// stop receiving location update when activity not visible/foreground
override fun onPause() {
super.onPause()
mapView.onPause()
stopLocationUpdates()
}
override fun onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
override public fun onLowMemory() {
super.onLowMemory();
mapView.onLowMemory()
}
override fun onMapReady(googleMap: GoogleMap?) {
map = googleMap!!
map.uiSettings?.isZoomControlsEnabled = true
map.isMyLocationEnabled = true
val marker = MarkerOptions().position(LatLng(lastLocation.latitude,lastLocation.longitude)).title("hello maps")
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
map.addMarker(marker)
val cameraPosition = CameraPosition.builder().target(LatLng(lastLocation.latitude,lastLocation.longitude)).zoom(12f).build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
private fun backFragment() {
val manager = (context as AppCompatActivity).supportFragmentManager
manager.popBackStackImmediate()
}
}
Кроме того, если бы кто-то мог просто заставить это работать с помощью менеджера местоположений или что-то еще, я был бы очень признателен. Или, может быть, ссылку или видео, где я мог бы следовать.
Большое спасибо!