0
내가 얻으려고하는 것은 사용자의 마지막 위치를 표시하는 것입니다. GPS가 비활성화 된 경우 위치 설정을 요청하십시오. 사용자가 확인을 누르면 GPS가 활성화되고지도 카메라가 발견 된 위치로 이동합니다.GoogleMap이 다시 초기화되지 않는 한 위치는 null입니다.
GPS가 이미 활성화되어 있으면 예상대로 작동합니다. 그러나 그렇지 않은 경우지도 카메라는 위치가 null이므로 이동하지 않습니다. 나는 displayLocation()
기능 내부 else
문 (location == null
) 후 initMap()
를 추가하는 경우
나는이 일을 할 수 있지만, 어떤이 솔루션에 대한 느낌이 좋지 않습니다.
누군가가 여기에 무슨 일이 일어 났는지 설명해 주시겠습니까? 나는 그것을 매우 감사한다! 활동이 시작되면 그런데
, 나는 MVP 아키텍처를 사용하고 있으므로, 호출되는 첫 번째 함수는 requestPermission()
class MainActivity : AppCompatActivity(), MainView, OnMapReadyCallback {
private val ZOOM_LEVEL = 12
private val ZOOM_DURATION = 2000
private val PERMISSION_REQUEST_CODE = 101
private val SETTINGS_REQUEST_CODE = 102
private val RC_SIGN_IN = 123
private lateinit var mMainPresent: MainPresenterImpl
private lateinit var mGoogleMap: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mMainPresent = MainPresenterImpl(this)
mMainPresent.onCreate()
}
override fun onResume() {
super.onResume()
mMainPresent.onResume()
}
override fun onPause() {
super.onPause()
mMainPresent.onPause()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST_CODE -> {
if (grantResults.isEmpty() || grantResults[0] == PackageManager.PERMISSION_DENIED) {
finish()
} else {
initMap()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
SETTINGS_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK) {
initMap()
}
}
}
}
override fun onMapReady(googleMap: GoogleMap) {
mGoogleMap = googleMap
displayLocation()
}
override fun displayLoginMethods() {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(!BuildConfig.DEBUG) // disables it for debug
.setAvailableProviders(
Arrays.asList<AuthUI.IdpConfig>(AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build(),
AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build()))
.build(),
RC_SIGN_IN)
}
override fun requestPermission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_CODE)
}
} else {
requestLocationSettings()
}
}
override fun displayLocation() {
val mFusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
try {
mGoogleMap.isMyLocationEnabled = true
mGoogleMap.uiSettings.isMyLocationButtonEnabled = true
mFusedLocationClient.lastLocation
.addOnSuccessListener(this) { location ->
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
val latitude = location.latitude
val longitude = location.longitude
val coordinate = LatLng(latitude, longitude)
mGoogleMap.addMarker(MarkerOptions().position(coordinate))
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(coordinate))
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL.toFloat()), ZOOM_DURATION, null)
} else {
Log.d("displayLocation", "location = null")
}
}
} catch (e: SecurityException) {
Log.e("Exception: %s", e.message)
}
}
/**
* Initiates Google Map. Once it's ready it calls the onMapReady method
*/
override fun initMap() {
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
private fun createLocationRequest(): LocationRequest {
val locationRequest = LocationRequest()
locationRequest.interval = 10000
locationRequest.fastestInterval = 5000
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
return locationRequest
}
private fun requestLocationSettings() {
val builder = LocationSettingsRequest.Builder().addLocationRequest(createLocationRequest())
val client = LocationServices.getSettingsClient(this)
val task = client.checkLocationSettings(builder.build())
task.addOnSuccessListener(this) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
initMap()
}
task.addOnFailureListener(this) { e ->
if (e is ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
e.startResolutionForResult([email protected], SETTINGS_REQUEST_CODE)
} catch (sendEx: IntentSender.SendIntentException) {
// Ignore the error.
}
}
}
}
} 다음 콜백 할 때 사용할 수있다