尝试在Kotlin中使用mapbox获取我的当前位置时出现KotlinNullPointerException

时间:2019-10-26 14:57:34

标签: android kotlin mapbox mapbox-android

尝试获取当前位置并将Latlng数据保存到变量中,以便以后使用,我只是将mapbox SDK与enableLocationComponent一起使用,这是我的代码m使用:


    private var myCurrentLocation: LatLng? = null



    @SuppressLint("MissingPermission")
    private fun enableLocationComponent(loadedMapStyle: Style) {
// Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(this)) {

// Create and customize the LocationComponent's options
            val customLocationComponentOptions = LocationComponentOptions.builder(this)
                .trackingGesturesManagement(true)
                .accuracyColor(ContextCompat.getColor(this, R.color.colorGreen))
                .build()

            val locationComponentActivationOptions =
                LocationComponentActivationOptions.builder(this, loadedMapStyle)
                    .locationComponentOptions(customLocationComponentOptions)
                    .build()


// Get an instance of the LocationComponent and then adjust its settings
            mapboxMap.locationComponent.apply {

                // Activate the LocationComponent with options
                activateLocationComponent(locationComponentActivationOptions)

// Enable to make the LocationComponent visible
                isLocationComponentEnabled = true

// Set the LocationComponent's camera mode
                cameraMode = CameraMode.TRACKING

// Set the LocationComponent's render mode
                renderMode = RenderMode.COMPASS

                myCurrentLocation = LatLng(
                    mapboxMap.locationComponent.lastKnownLocation?.latitude!!,
                    mapboxMap.locationComponent.lastKnownLocation!!.longitude)
            }
        } else {
            permissionsManager = PermissionsManager(this)
            permissionsManager.requestLocationPermissions(this)
        }

    }

稍后,当我尝试运行此代码块时,出现错误消息:

            val myPosition = CameraPosition.Builder()
                .target(myCurrentLocation)
                .zoom(14.0)
                .tilt(20.0)
                .build()
            mapboxMap.animateCamera(
                CameraUpdateFactory
                    .newCameraPosition(myPosition), 7000
            )

错误是kotlin.KotlinNullPointerException指向行myCurrentLocation = LatLng( mapboxMap.locationComponent.lastKnownLocation?.latitude!!, mapboxMap.locationComponent.lastKnownLocation!!.longitude)

0 个答案:

没有答案