Anonymous
Как показать маркер текущего положения на карте в Android (Kotlin)?
Сообщение
Anonymous » 21 май 2024, 15:51
Я пытаюсь добавить маркер к моему текущему местоположению на карте, но по какой-то причине мое текущее местоположение имеет значение null, хотя в моем эмуляторе включено определение моего местоположения. Похоже, проблема также связана с разрешениями на определение местоположения, потому что, когда я отключаю свое местоположение, разрешения на определение местоположения остаются предоставленными. Однако я не могу понять, в чем проблема.
Код: Выделить всё
private const val FINE_PERMISSION_CODE = 1
private lateinit var myMap : GoogleMap
private lateinit var currentLocation : Location
private lateinit var fusedLocationProviderClient : FusedLocationProviderClient
class MapActivity : AppCompatActivity(), OnMapReadyCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
private fun getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), FINE_PERMISSION_CODE)
return
}
val task : Task = fusedLocationProviderClient.lastLocation
task.addOnSuccessListener { location : Location? ->
if (location != null) {
currentLocation = location
val mapFragment =
supportFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment
mapFragment.getMapAsync(this)
}
else {
Log.d("Location", "null location")
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == FINE_PERMISSION_CODE) {
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Log.d("Location", "location granted")
getCurrentLocation()
} else {
Toast.makeText(this, "Location Permission is denied, please allow the permission", Toast.LENGTH_SHORT).show()
}
}
}
override fun onMapReady(googleMap : GoogleMap) {
myMap = googleMap
var curLoc = LatLng(currentLocation.latitude, currentLocation.longitude)
Log.d("Location", currentLocation.latitude.toString() + currentLocation.longitude.toString())
myMap.addMarker(MarkerOptions().position(curLoc).title("My Location"))
myMap.moveCamera(CameraUpdateFactory.newLatLng(curLoc))
myMap.moveCamera(CameraUpdateFactory.zoomTo(12f))
// myMap.uiSettings.isZoomControlsEnabled = true
}
Я пытаюсь найти способ узнать свое текущее местоположение, потому что по какой-то причине здесь оно всегда оказывается нулевым.
Подробнее здесь:
https://stackoverflow.com/questions/785 ... oid-kotlin
1716295913
Anonymous
Я пытаюсь добавить маркер к моему текущему местоположению на карте, но по какой-то причине мое текущее местоположение имеет значение null, хотя в моем эмуляторе включено определение моего местоположения. Похоже, проблема также связана с разрешениями на определение местоположения, потому что, когда я отключаю свое местоположение, разрешения на определение местоположения остаются предоставленными. Однако я не могу понять, в чем проблема. [code]private const val FINE_PERMISSION_CODE = 1 private lateinit var myMap : GoogleMap private lateinit var currentLocation : Location private lateinit var fusedLocationProviderClient : FusedLocationProviderClient class MapActivity : AppCompatActivity(), OnMapReadyCallback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_map) fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) getCurrentLocation() } private fun getCurrentLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), FINE_PERMISSION_CODE) return } val task : Task = fusedLocationProviderClient.lastLocation task.addOnSuccessListener { location : Location? -> if (location != null) { currentLocation = location val mapFragment = supportFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment mapFragment.getMapAsync(this) } else { Log.d("Location", "null location") } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if(requestCode == FINE_PERMISSION_CODE) { if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Log.d("Location", "location granted") getCurrentLocation() } else { Toast.makeText(this, "Location Permission is denied, please allow the permission", Toast.LENGTH_SHORT).show() } } } override fun onMapReady(googleMap : GoogleMap) { myMap = googleMap var curLoc = LatLng(currentLocation.latitude, currentLocation.longitude) Log.d("Location", currentLocation.latitude.toString() + currentLocation.longitude.toString()) myMap.addMarker(MarkerOptions().position(curLoc).title("My Location")) myMap.moveCamera(CameraUpdateFactory.newLatLng(curLoc)) myMap.moveCamera(CameraUpdateFactory.zoomTo(12f)) // myMap.uiSettings.isZoomControlsEnabled = true } [/code] Я пытаюсь найти способ узнать свое текущее местоположение, потому что по какой-то причине здесь оно всегда оказывается нулевым. Подробнее здесь: [url]https://stackoverflow.com/questions/78509202/how-to-show-current-position-marker-on-map-in-android-kotlin[/url]