在我的手机上安装android 9之前,我正在使用Java,今天我决定重新开始使用该项目,但继续使用Kotlin。
由于某种原因,我当前位置周围的蓝点和圆圈没有显示(虽然以前在Java语法上可以使用)。
应用程序将我当前的位置居中,并且在右上角显示“显示我的位置”(如果按此按钮,则什么也没有发生)
这是我的代码。
package com.example.activitymap
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.places.GeoDataClient
import com.google.android.gms.location.places.PlaceDetectionClient
import com.google.android.gms.location.places.PlaceLikelihood
import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse
import com.google.android.gms.location.places.Places
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CameraPosition
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.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private val TAG = MapsActivity::class.java.simpleName
private var mMap: GoogleMap? = null
private var mCameraPosition: CameraPosition? = null
// The entry point to the Fused Location Provider.
private var mFusedLocationProviderClient: FusedLocationProviderClient? = null
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private val mDefaultLocation = LatLng(-33.8523341, 151.2106085)
private val DEFAULT_ZOOM = 15
private val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1
private var mLocationPermissionGranted: Boolean = false
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private var mLastKnownLocation: Location? = null
// Keys for storing activity state.
private val KEY_CAMERA_POSITION = "camera_position"
private val KEY_LOCATION = "location"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION)
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION)
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps)
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
// Build the map.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(map: GoogleMap) {
mMap = map
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap?.setInfoWindowAdapter(object : GoogleMap.InfoWindowAdapter {
override// Return null here, so that getInfoContents() is called next.
fun getInfoWindow(arg0: Marker): View? {
return null
}
override fun getInfoContents(marker: Marker): View {
// Inflate the layouts for the info window, title and snippet.
val infoWindow = layoutInflater.inflate(
R.layout.custom_info_contents,
findViewById<FrameLayout>(R.id.map), false
)
val title = infoWindow.findViewById(R.id.title) as TextView
title.text = marker.title
val snippet = infoWindow.findViewById(R.id.snippet) as TextView
snippet.text = marker.snippet
return infoWindow
}
})
mMap?.setOnMapClickListener { latLng ->
mMap?.addMarker(
MarkerOptions()
.position(latLng)
)
openAddActivity(latLng)
}
// Prompt the user for permission.
getLocationPermission()
// Turn on the My Location layer and the related control on the map.
updateLocationUI()
// Get the current location of the device and set the position of the map.
getDeviceLocation()
}
private fun getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
val locationResult = mFusedLocationProviderClient?.lastLocation
locationResult?.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.result
mMap?.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(
mLastKnownLocation!!.latitude,
mLastKnownLocation!!.longitude
), DEFAULT_ZOOM.toFloat()
)
)
mMap?.isMyLocationEnabled = true
mMap?.uiSettings?.isMyLocationButtonEnabled = true
} else {
Log.d(TAG, "Current location is null. Using defaults.")
Log.e(TAG, "Exception: %s", task.exception)
mMap?.moveCamera(
CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM.toFloat())
)
mMap?.uiSettings?.isMyLocationButtonEnabled = false
}
}
}
} catch (e: SecurityException) {
Log.e("Exception: %s", e.message)
}
}
/**
* Prompts the user for permission to use the device location.
*/
private fun getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(
this.applicationContext,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
mLocationPermissionGranted = true
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION
)
}
}
/**
* Handles the result of the request for location permissions.
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
mLocationPermissionGranted = false
when (requestCode) {
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true
}
}
}
updateLocationUI()
}
private fun openAddActivity(latlng: LatLng) {
val intent = Intent(this, AddActivity::class.java)
val args = Bundle()
args.putParcelable("latLng", latlng)
intent.putExtra("bundle", args)
this@MapsActivity.startActivity(intent)
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private fun updateLocationUI() {
if (mMap == null) {
return
}
try {
if (mLocationPermissionGranted) {
mMap?.isMyLocationEnabled = true
mMap?.uiSettings?.isMyLocationButtonEnabled = true
} else {
mMap?.isMyLocationEnabled = false
mMap?.uiSettings?.isMyLocationButtonEnabled = false
mLastKnownLocation = null
getLocationPermission()
}
} catch (e: SecurityException) {
Log.e("Exception: %s", e.message)
}
}
}
Build.Gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.activitymap"
minSdkVersion 23
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.android.gms:play-services:12.0.1'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:mediarouter-v7:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:multidex:1.0.3'
}