在Android中使用Mapbox获取当前的x,y坐标

时间:2019-01-15 07:53:28

标签: android error-handling nullpointerexception mapbox

大家好,我试图以x,y坐标获取当前gps位置,以便计算应用程序中的一些有用内容。我如上所述使用了定位引擎,但是当我运行代码时,它向我返回错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.android.core.location.LocationEngine.setInterval(int)' on a null object reference
        at mapboxapp.hello.com.mapboxapp.MainActivity.enableLocationComponent(MainActivity.java:87)
        at mapboxapp.hello.com.mapboxapp.MainActivity.onMapReady(MainActivity.java:78)
        at com.mapbox.mapboxsdk.maps.MapView$MapCallback.onMapReady(MapView.java:1648)
        at com.mapbox.mapboxsdk.maps.MapView$MapCallback.onDidFinishLoadingStyle(MapView.java:1686)
        at com.mapbox.mapboxsdk.maps.MapChangeReceiver.onDidFinishLoadingStyle(MapChangeReceiver.java:195)
        at com.mapbox.mapboxsdk.maps.NativeMapView.onDidFinishLoadingStyle(NativeMapView.java:1002)

我不明白确切的错误是因为空指针异常是一般性的。你能帮我吗?到目前为止,这是我所做的:

public class MainActivity extends AppCompatActivity implements
        OnMapReadyCallback, PermissionsListener, OnLocationClickListener, OnCameraTrackingChangedListener {

private PermissionsManager permissionsManager;
private MapboxMap mapboxMap;
private MapView mapView;
private LocationComponent locationComponent;
private boolean isInTrackingMode;
private LocationEngine locationEngine;
private Location mCurrentLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Mapbox access token is configured here. This needs to be called either in your application
    // object or in the same activity which contains the mapview.
    Mapbox.getInstance(this, getString(R.string.access_token));

    // This contains the MapView in XML and needs to be called after the access token is configured.
    setContentView(R.layout.activity_main);

    Log.d("LocOptionsActivity", "isInTrackingMode = " + isInTrackingMode);


    mapView = findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(this);

}

@Override
public void onMapReady(MapboxMap mapboxMap) {
    MainActivity.this.mapboxMap = mapboxMap;
    enableLocationComponent();

}




// @SuppressLint("WrongConstant")
    @SuppressWarnings( {"MissingPermission"})
    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);
        locationEngine.addLocationEngineListener(new LocationEngineListener() {
            @SuppressLint("MissingPermission")
        @Override
        public void onConnected() {
            locationEngine.requestLocationUpdates();
        }

        @Override
        public void onLocationChanged(Location location) {
            mCurrentLocation = location;
        }
    });
    locationEngine.activate();
    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {
        //
        LocationComponentOptions options = LocationComponentOptions.builder(this)
                .elevation(5)
                .accuracyAlpha(.6f)
                .accuracyColor(Color.RED)
                .foregroundDrawable(R.drawable.gps)
                .build();

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

        //Location Engine
        locationComponent.setLocationEngine(locationEngine);

        // Activate
        locationComponent.activateLocationComponent(this);

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

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


        // Set the component's render mode
        locationComponent.setRenderMode(RenderMode.GPS);

        // Add the location icon click listener
        locationComponent.addOnLocationClickListener(this);

        // Add the camera tracking listener. Fires if the map camera is manually moved.
        locationComponent.addOnCameraTrackingChangedListener(this);

        //Set the component's zoom level
        locationComponent.zoomWhileTracking(22);

    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}

@SuppressWarnings( {"MissingPermission"})
@Override
public void onLocationComponentClick() {
    if (locationComponent.getLastKnownLocation() != null) {
        Toast.makeText(this, String.format(getString(R.string.current_location),
                 locationComponent.getLastKnownLocation().getLatitude(),
               locationComponent.getLastKnownLocation().getLongitude()), Toast.LENGTH_LONG).show();
    }

}
@Override
public void onCameraTrackingDismissed() {
    isInTrackingMode = false;

}

@Override
public void onCameraTrackingChanged(int currentMode) {
    // Empty on purpose
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
    Toast.makeText(this, "This app needs location permissions in order to show its functionality", Toast.LENGTH_LONG).show();
}

@Override
public void onPermissionResult(boolean granted) {
    if (granted) {
        enableLocationComponent();
    } else {
        Toast.makeText(this, "You didn't grant location permissions.", Toast.LENGTH_LONG).show();
        finish();
    }
}


@Override
@SuppressWarnings( {"MissingPermission"})
protected void onStart() {
    super.onStart();
    mapView.onStart();
}

@Override
protected void onResume() {
    super.onResume();
    mapView.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    mapView.onPause();
}

@Override
protected void onStop() {
    super.onStop();
    mapView.onStop();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}

}

1 个答案:

答案 0 :(得分:1)

 @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                    return;
                }
            });
        } else {
            Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
            mapView.onStart();
        }
    }