Код: Выделить всё
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