使用mapbox

时间:2019-05-14 20:48:35

标签: java android-studio-3.0

当我使用mapbox时,我遇到了与GPS相关的问题。

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,PermissionsListener {

    FirebaseAuth auth;

    private MapView mapView;
    private MapboxMap mapboxMap;
    private PermissionsManager permissionsManager;
    Location originLocation;
    LocationEngine locationEngine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "pk.eyJ1Ijoibml0eWFhcm9yYTcyIiwiYSI6ImNqcHpqeDdjYjAwenU0OG82MDBuZWxtdGIifQ.mMPtHap9shSb-WWzZFyPew");
        setContentView(R.layout.activity_main);

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

        /*CameraPosition position = new CameraPosition.Builder()
                .target(new LatLng(25.3254275, 83.0088737))
                .zoom(14)
                .tilt(20)
                .build();*/

        auth = FirebaseAuth.getInstance();

        mapView.getMapAsync(this);
            /*@Override
            public void onMapReady(MapboxMap mapboxMap) {

                mapboxMap.addMarker(new MarkerOptions()
                    .position(new LatLng(25.3254275,83.0088737))
                    .title("My Location")
                    .snippet("bro"));


                mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 200);*/


    }


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

        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

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

    }

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

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

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

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

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

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

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

        Toast.makeText(this, "Explanation needed", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onPermissionResult(boolean granted) {

        if (granted) {
            initializeLocationEngine();
            enableLocationComponent();
        } else {
            Toast.makeText(this, "Permission Needed", Toast.LENGTH_LONG).show();
            finish();
        }

    }

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

    }

    void locationEnable() {
        if (PermissionsManager.areLocationPermissionsGranted(this)) {
            initializeLocationEngine();
            enableLocationComponent();
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }


    @SuppressWarnings({"MissingPermission"})
    private void enableLocationComponent() {

        if (PermissionsManager.areLocationPermissionsGranted(this)) {


            Location lastLocation = locationEngine.getLastLocation();

            FirebaseUser firebaseUser = auth.getCurrentUser();
            String userId = firebaseUser.getUid();

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userId);

            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    HashMap user = (HashMap) dataSnapshot.getValue();
                    Log.i("userid", user.get("userId").toString());
                    Log.i("username", user.get("username").toString());

                    reference.child("latLng").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            Log.i("userblaa", dataSnapshot.toString());
                            if(lastLocation!=null){
                                originLocation=lastLocation;
                            }
                            Log.i("Location",String.valueOf(lastLocation.getLatitude())+lastLocation.getLongitude());


                            LatLng latLng = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());

                            IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
                            Bitmap iconDrawable = BitmapFactory.decodeResource(getResources(),R.drawable.marker);
                            iconDrawable=Bitmap.createScaledBitmap(iconDrawable, 70, 70, true);
                            com.mapbox.mapboxsdk.annotations.Icon icon=iconFactory.fromBitmap(iconDrawable);

                            mapboxMap.addMarker(new MarkerOptions()
                                    .position(new LatLng(originLocation.getLatitude(), originLocation.getLongitude()))
                                    .setIcon(icon)
                                    );

                            mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                                    new LatLng(originLocation.getLatitude(), originLocation.getLongitude()), 12));

                            reference.child("latLng").setValue(latLng);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                    //Log.i("userlatlng",user.getLatLng().getLatitude()+" "+user.getLatLng().getLongitude());

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

此错误消息:

  

E / Android运行时:致命异常:主要       流程:com.example.nitya.starein,PID:8819       java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'double android.location.Location.getLatitude()'           在com.example.nitya.starein.MainActivity $ 1 $ 1.onDataChange(MainActivity.java:210)           com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database @@ 16.0.5:75)           com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database @@ 16.0.5:63)           在com.google.firebase.database.core.view.EventRaiser $ 1.run(com.google.firebase:firebase-database @@ 16.0.5:55)           在android.os.Handler.handleCallback(Handler.java:739)           在android.os.Handler.dispatchMessage(Handler.java:95)           在android.os.Looper.loop(Looper.java:148)           在android.app.ActivityThread.main(ActivityThread.java:5417)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

似乎“ originLocation”没有用“ lastLocation”初始化,可能是因为“ lastLocation”也为null。