MapBox:在LocationComponent上获取lattitude()和longitude()

时间:2019-01-23 14:44:20

标签: java android mapbox

我在使用locationComponent()获取设备位置的latitude()和longitude()时遇到麻烦。我正在从旧版本的MapBox SDK迁移到最新的版本7.0.1

我已经尝试过寻找答案,但是仍然不能完全满足我的需要。

这是我的代码:

 private void enableLocationComponent() {
    locationEngine = new LocationEngineProvider(this).obtainLocationEngineBy(LocationEngine.Type.GOOGLE_PLAY_SERVICES);
    locationEngine.setInterval(1000);//this is means get location every 1 second
    locationEngine.setFastestInterval(1000);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);

    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {

        // Get an instance of the component
        LocationComponent locationComponent = mapboxMap.getLocationComponent();
        locationComponent.getLastKnownLocation();

        // Activate
        locationComponent.activateLocationComponent(this,mapboxMap.getStyle());

        // Enable to make component visible
        locationComponent.setLocationComponentEnabled(true);

        // Set the component's camera mode
        locationComponent.setCameraMode(CameraMode.TRACKING);

        // Set the component's render mode
        locationComponent.setRenderMode(RenderMode.COMPASS);
    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}

我希望这个问题能够得到解决,或者告诉我我错过了什么,并简要解释一下。谢谢!

依赖项:

 // Mapbox Maps SDK dependency
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:7.0.1'

// Mapbox Services SDK dependency to retrieve direction routes
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-services:4.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:4.3.0'

1 个答案:

答案 0 :(得分:0)

您应该致电

locationEngine.getLastLocation(new LocationEngineCallback<LocationEngineResult>() {
  @Override
  public void onSuccess(LocationEngineResult result) {
    Location location = result.getLastLocation();
    if (location != null) {
      // process last location
    }
  }

  @Override
  public void onFailure(@NonNull Exception exception) {
    // failure
  }
});

上面是一个异步调用,它将返回最后一个已知设备的位置。

另一方面,

locationComponent.getLastKnownLocation();

将返回该组件在地图上的最后一个已知/显示的位置,在您的情况下,该位置始终为null,因为您尚未激活或启用该组件。

首次激活,启用并显示该组件后,它将进行相同的异步调用以建立当前位置。之后,在大多数前景情况下,您都可以依赖组件的最后已知位置,但是要确定初始用户的位置,您一定要使用LocationEngine