Kotlin中如何在含MapView的Fragment内获取并实时更新用户当前位置
基于GoogleApiClient的位置获取与实时更新实现
核心缺失逻辑补全
当前代码仅实现了GoogleApiClient的相关回调接口,未完成客户端实例初始化,也未关联位置服务API,这是无法获取位置的核心原因,需要按以下流程补全:
- 在类成员区新增需要的依赖对象
private lateinit var googleApiClient: GoogleApiClient private lateinit var locationRequest: LocationRequest private var currentLocation: Location? = null // 位置更新回调,接收系统返回的最新位置 private val locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { super.onLocationResult(locationResult) currentLocation = locationResult.lastLocation // 拿到最新位置后更新地图标记与相机视角 updateMapLocation(currentLocation) } } - 在Fragment生命周期中完成GoogleApiClient的创建、连接与断开
- 在
onStart()中初始化并连接客户端,关联位置服务override fun onStart() { super.onStart() mapView?.onStart() // 构建GoogleApiClient实例,关联位置服务API googleApiClient = GoogleApiClient.Builder(requireContext()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build() googleApiClient.connect() - 在
onStop()中断开连接,移除位置回调,避免后台无效耗电override fun onStop() { super.onStop() mapView?.onStop() if (googleApiClient.isConnected) { LocationServices.getFusedLocationProviderClient(requireContext()) .removeLocationUpdates(locationCallback) googleApiClient.disconnect() } }
- 在
位置获取与实时更新实现
在onConnected()回调中完成位置拉取、更新规则配置,注意所有位置API调用前必须完成权限检查,否则会触发SecurityException导致崩溃:
override fun onConnected(p0: Bundle?) { // 运行时权限校验 if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { checkLocationPermission() return } // 1. 先拉取最近一次的已知位置,避免等待首次更新的空窗期 LocationServices.getFusedLocationProviderClient(requireContext()) .lastLocation .addOnSuccessListener { location -> currentLocation = location updateMapLocation(currentLocation) } // 2. 配置实时位置更新规则 locationRequest = LocationRequest.create().apply { // 高精度模式,适合导航场景;普通场景可替换为PRIORITY_BALANCED_POWER_ACCURACY降低耗电 priority = LocationRequest.PRIORITY_HIGH_ACCURACY // 最长更新间隔10秒 interval = 10000 // 最快更新间隔5秒,避免接收过频繁的回调 fastestInterval = 5000 } // 3. 发起实时位置更新请求 LocationServices.getFusedLocationProviderClient(requireContext()) .requestLocationUpdates(locationRequest, locationCallback, null) // 4. 开启地图自带的位置展示层 gMap?.isMyLocationEnabled = true gMap?.uiSettings?.isMyLocationButtonEnabled = true }
- 抽离公共的地图位置更新逻辑,避免代码重复
private fun updateMapLocation(location: Location?) { location ?: return val userLatLng = LatLng(location.latitude, location.longitude) // 清空旧标记(不需要保留历史标记可调用clear) gMap?.clear() // 添加用户当前位置标记 gMap?.addMarker(MarkerOptions().position(userLatLng).title("我的位置")) // 平滑移动相机到用户位置,缩放级别15可根据场景调整 gMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(userLatLng, 15f)) }
现有代码优化与问题修复
- 删除重复调用逻辑:原代码在
onCreateView中,if块内外两次调用checkLocationPermission(),属于重复逻辑,保留if块内的调用,删除外部那次。 - 修复MapView生命周期错误:
- 删除
onCreateView中提前调用的mapView!!.onResume(),MapView的生命周期回调需与Fragment严格对齐,提前调用会导致内部状态异常。 - 将
mapView!!.onCreate(null)中的参数替换为传入的savedInstanceState,避免地图状态恢复异常。
- 删除
- 删除冗余代码:移除
onMapReady中重复初始化的MapsInitializer.initialize(context),MapView创建时已自动完成SDK初始化。 - 补充权限回调处理:重写
onRequestPermissionsResult,用户授权通过后重新连接位置服务,解决授权后无法立刻获取位置的问题override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (!googleApiClient.isConnecting && !googleApiClient.isConnected) { googleApiClient.connect() } } } } - 补全未实现的异常回调,替换原有的TODO占位逻辑:
override fun onConnectionSuspended(p0: Int) { // 连接挂起时自动重连 googleApiClient.connect() } override fun onConnectionFailed(p0: ConnectionResult) { // 连接失败时可添加日志上报,或弹窗提示用户位置服务不可用 } - 替换所有
!!强断言的空值调用,改用?.安全调用,避免空指针崩溃。
内容的提问来源于stack exchange,提问作者user3761485
相关产品推荐
相关产品推荐

