未触发地图位置更改侦听器
Posted
技术标签:
【中文标题】未触发地图位置更改侦听器【英文标题】:Maps location change listener not triggered 【发布时间】:2020-08-27 22:45:19 【问题描述】:我正在开发一个包含 Google 地图的应用程序。地图可以找到我的位置并在其上放置标记。但我写了 onLocationChangeListener 和。 Toast 显示我的坐标(经度高度)。但它不会在屏幕上呈现任何吐司,我不明白为什么。它应该渲染一个 toast 以显示我在更改和第一次找到时的坐标。
地图活动
class MapsActivity : AppCompatActivity(), OnMapReadyCallback, IOnLoadLocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
private var mMap: GoogleMap? = null
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private var currentMarker: Marker? = null
private lateinit var myLocationRef: DatabaseReference
private lateinit var dangerousArea: MutableList<LatLng>
private lateinit var listener: IOnLoadLocationListener
private var photoUrl: String? = null
private lateinit var myCity: DatabaseReference
private lateinit var lastLocation: Location
private var geoQuery: GeoQuery? = null
private lateinit var geoFire: GeoFire
private lateinit var locationManager: LocationManager
private lateinit var latLng: LatLng
private lateinit var location: Location
private lateinit var locationListener: LocationListener
private lateinit var mLocation : Location
private lateinit var mGoogleApiClient : GoogleApiClient
private var UPDATE_INTERVAL: Long = 2000
private var FASTEST_INTERVAL: Long = 5000
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(com.example.huaweichallange.R.layout.activity_maps)
val personInfo = intent.extras!!.get("extra") as UserInfoModel
photoUrl = personInfo.personPhoto
Dexter.withActivity(this)
.withPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(object : PermissionListener
override fun onPermissionGranted(response: PermissionGrantedResponse?)
buildLocationRequest()
buildLocationCallBack()
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this@MapsActivity)
initArea()
settingGeoFire()
override fun onPermissionRationaleShouldBeShown(
permission: com.karumi.dexter.listener.PermissionRequest?,
token: PermissionToken?
)
override fun onPermissionDenied(response: PermissionDeniedResponse?)
Toast.makeText(
this@MapsActivity,
"You must enable this permission",
Toast.LENGTH_SHORT
).show()
).check()
private fun settingGeoFire()
myLocationRef = FirebaseDatabase.getInstance().getReference("MyLocation")
geoFire = GeoFire(myLocationRef)
private fun initArea()
myCity = FirebaseDatabase.getInstance()
.getReference("DangerousArea").child("MyCity")
listener = this
myCity.addValueEventListener(object : ValueEventListener
override fun onCancelled(p0: DatabaseError)
override fun onDataChange(dataSnapshot: DataSnapshot)
val latLngList = ArrayList<MyLatlng>()
for (locationSnapShot in dataSnapshot.children)
val latLng = locationSnapShot.getValue(MyLatlng::class.java)
latLngList.add(latLng!!)
listener.onLocationLoadSuccess(latLngList)
)
private fun buildLocationCallBack()
locationCallback = object : LocationCallback()
override fun onLocationResult(locationResult: LocationResult?)
super.onLocationResult(locationResult)
if (mMap != null)
lastLocation = locationResult!!.lastLocation
addUserMarker()
private fun addUserMarker()
geoFire.setLocation(
"You",
GeoLocation(lastLocation.latitude, lastLocation.longitude)
) _, _ ->
if (currentMarker != null) currentMarker!!.remove()
currentMarker = mMap!!.addMarker(
MarkerOptions().position(
LatLng(
lastLocation.latitude,
lastLocation.longitude
)
).title("You").icon(BitmapDescriptorFactory.fromBitmap(getBitmap(photoUrl)))
)
mMap!!.animateCamera(CameraUpdateFactory.newLatLngZoom(currentMarker!!.position, 12.0f))
fun getBitmap(url : String?) : Bitmap?
var bmp : Bitmap ? = null
Picasso.get().load(url).into(object : com.squareup.picasso.Target
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?)
bmp = bitmap
override fun onPrepareLoad(placeHolderDrawable: Drawable?)
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?)
)
return bmp
private fun buildLocationRequest()
locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 500
locationRequest.fastestInterval = 300
locationRequest.smallestDisplacement = 5f
override fun onMapReady(googleMap: GoogleMap)
mMap = googleMap
mMap!!.uiSettings.isZoomControlsEnabled = true
if (fusedLocationProviderClient != null)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.myLooper()
)
val pref= this@MapsActivity.getSharedPreferences("darkMode", Context.MODE_PRIVATE)
val darkMode = pref.getString("darkMode","dark")
if(darkMode!=null)
useDarkMode(googleMap)
private fun useDarkMode(googleMap: GoogleMap?)
try
val success : Boolean = googleMap!!.setMapStyle(
MapStyleOptions.
loadRawResourceStyle(this, com.example.huaweichallange.R.raw.map_style))
catch (e: Resources.NotFoundException)
Log.e("MapActivity","Map Style Cannot found")
override fun onLocationLoadSuccess(latLng: List<MyLatlng>)
dangerousArea = ArrayList()
for (myLatLng in latLng)
val convert = LatLng(myLatLng.latitude, myLatLng.longitude)
dangerousArea.add(convert)
val mapFragment = supportFragmentManager
.findFragmentById(com.example.huaweichallange.R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
if (mMap != null)
mMap!!.clear()
addUserMarker()
override fun onLocationLoadFailed(message: String)
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show()
override fun onStop()
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
super.onStop()
override fun onConnected(p0: Bundle?)
override fun onConnectionSuspended(p0: Int)
override fun onConnectionFailed(p0: ConnectionResult)
override fun onLocationChanged(location: Location?)
val msg : String = "Updated Location: " + lastLocation!!.longitude+","+ lastLocation!!.latitude
Toast.makeText(this@MapsActivity, msg.toDouble().toString(), Toast.LENGTH_SHORT).show()
latLng = LatLng(location!!.latitude, location!!.longitude)
val mapFragment : SupportMapFragment = supportFragmentManager.findFragmentById(com.example.huaweichallange.R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
【问题讨论】:
也许你可以通过移动你的设备来尝试一下,这可以触发onLocationChanged。地图可能已经获取了您设备的最后一个已知位置。 @DhavalShah 我连接了我的实际设备并走进屋内,但什么也没发生。 【参考方案1】:您没有将您的活动设置为位置侦听器。您的活动实现了com.google.android.gms.location.LocationListener
接口,但是您将另一个回调(locationCallback
)传递给您的fusedLocationProviderClient
:
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback, // you should replace this with your activity instance
Looper.myLooper()
)
到:
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
this, // your activity instance - this
Looper.myLooper()
)
那么你应该在你的onLocationChanged
回调中拦截位置变化:
override fun onLocationChanged(location: Location?)
Log.v("your_tag", "Latitude:$location.latitude, Longitude:$location.longitude")
【讨论】:
但 fusedLocationProviderClient.requestLocationUpdates 需要 3 个参数“locationRequest、LocationCallback、Looper”。当我写“this”时,它会给出错误类型不匹配。 我也改为“this.locationCallback”,但也没有发生任何事情。 您尝试过 this@MapsActivity 吗? 是的,但是没有用。我只是将 toast 移到 buildLocationCallback 函数内部,它起作用了。 这不是你问的,onLocationResult 在设备位置信息可用时触发,而不是每次位置变化时触发以上是关于未触发地图位置更改侦听器的主要内容,如果未能解决你的问题,请参考以下文章
Flutter Application Bloc 侦听器未接收到状态更新