如何在没有MapBoxMap实例的情况下跟踪MapBox中的设备位置

问题描述

如何在不实例化mapBoxmap对象的情况下启用位置组件。我看到的唯一方法涉及调用mapBoxmap getLocationComponent()方法。像这样:

LocationComponent locationComponent = mapBoxMap.getLocationComponent();

但是我的用例不需要显示地图。我只对坐标感兴趣。

解决方法

答案:https://docs.mapbox.com/android/core/overview/#installation。 我的实现片段:

    private void enableLocationComponent() {
        if (PermissionsManager.areLocationPermissionsGranted(getActivity())) {
            LocationEngineRequest request = new LocationEngineRequest.Builder(DEFAULT_INTERVAL_IN_MILLISECONDS)
                    .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
                    .setMaxWaitTime(DEFAULT_MAX_WAIT_TIME)
                    .build();
            locationEngine.requestLocationUpdates(request,callback,Looper.getMainLooper());
            locationEngine.getLastLocation(callback);
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(getActivity());
        }
    }


    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {

    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            // Permission sensitive logic called here,such as activating the Maps SDK's LocationComponent to show the device's location
            enableLocationComponent();
        } else {
            // User denied the permission
        }
    }


    private static class LocationListeningCallback
            implements LocationEngineCallback<LocationEngineResult> {

        private final WeakReference<Fragment> fragmentWeakReference;

        LocationListeningCallback(Fragment fragment) {
            this.fragmentWeakReference = new WeakReference<>(fragment);
        }

        @Override
        public void onSuccess(LocationEngineResult result) {

            // The LocationEngineCallback interface's method which fires when the device's location has changed.
            Location lastLocation = result.getLastLocation();
            if (lastLocation != null) {
                Log.e(LOG_TAG,"location: " + lastLocation.toString());
                if (lastLocation.hasAccuracy()) {

                }
            }
        }

        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(LOG_TAG,"failed to get device location");

            // The LocationEngineCallback interface's method which fires when the device's location can not be captured
        }
    }```