尝试获取用户位置时未初始化MapBox Map。科特林

时间:2020-09-28 10:53:27

标签: android kotlin mapbox

我正在尝试使用MapBox在android中获取用户位置。我的地图在片段中。这就是我初始化它的方式。

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?

): View? {
    // Inflate the layout for this fragment

    val root = inflater.inflate(R.layout.fragment_second, container, false)
    mapView = root.findViewById(R.id.map_view)
    mapView?.onCreate(savedInstanceState)
    mapView?.getMapAsync { mapboxMap ->

        mapboxMap.setStyle(Style.MAPBOX_STREETS) {
            enableLocationComponent(it)
        }
    }
    return root
}

当我尝试调用 enableLocationComponent(it)时,应用程序崩溃了。通常,当我从 onMapReady()调用它时,它可以正常工作。但这是不同的情况。我真的不知道将 enableLocationComponent(it)

放在哪里

2 个答案:

答案 0 :(得分:0)

您可以检查是否通过设置布尔值onMapReady()来调用true,然后运行enableLocationComponent(it) :)) 或在onMapReady()中调用Handler在所需的位置运行enableLocationComponent(it)

类似这样的东西:

var mapLoaded = false
override fun onMapReady(@NonNull mapboxMap:MapboxMap) {
        this.mapboxMap = mapboxMap
        mapboxMap.setStyle(Style.Builder().fromUri(Style.MAPBOX_STREETS)
            .withSource(GeoJsonSource(CIRCLE_GEOJSON_SOURCE_ID))
            .withSource(GeoJsonSource(LINE_GEOJSON_SOURCE_ID)), object:Style.OnStyleLoaded {
            override fun onStyleLoaded(@NonNull style1:Style) {
                mapLoaded = true //then chack this value if is ture call enableLocationComponent(it)
            }
        })
    }

        lateinit var mHandler : Handler
    
    // initialize this where you want call your function
        mHandler = object:Handler(Looper.getMainLooper()) {
              override fun handleMessage(message:Message) {
                   enableLocationComponent(it)
              }
        }

//onMapReady bi like this
        override fun onMapReady(@NonNull mapboxMap:MapboxMap) {
             this.mapboxMap = mapboxMap
             mapboxMap.setStyle(Style.Builder().fromUri(Style.MAPBOX_STREETS)
                  .withSource(GeoJsonSource(CIRCLE_GEOJSON_SOURCE_ID))
                  .withSource(GeoJsonSource(LINE_GEOJSON_SOURCE_ID)), object:Style.OnStyleLoaded {
                   override fun onStyleLoaded(@NonNull style1:Style) {
                          mHandler.sendEmptyMessage(0)
                     }
                })
           }

答案 1 :(得分:0)

所以我终于找到了解决方案。

我不得不将样式集从片段 onCreateView 移到 onMapReady 函数。然后我可以调用 enableLocationComponent()

最终代码如下:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?

): View? {
    // Inflate the layout for this fragment

    val root = inflater.inflate(R.layout.fragment_second, container, false)
    mapView = root.findViewById(R.id.map_view)
    mapView?.onCreate(savedInstanceState)
    mapView?.getMapAsync(this)
    return root
}

override fun onMapReady(mapboxMap: MapboxMap) {
    this.mapboxMap = mapboxMap
    mapboxMap.setStyle(Style.MAPBOX_STREETS) {
        enableLocationComponent(it)
    }
}