Apertura APP show della mia posizione corrente

di il
1 risposte

Apertura APP show della mia posizione corrente

Prendo lat e long da Firebase, però ogni volta che apro l'app mi mostra la mappa sullo 0,0. Come posso inizializzare la mappa dalla mia posizione corrente?

Naturalmente in futuro la posizione corrente va settata su Firebase su tutti i client, il problema che se lo facessi già ora starei fermo sulla mia posizione e non ho modo poi di fare una prova per spostarmi. Per ora voglio limitarmi un'attimo a questo.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private DatabaseReference databaseReference;
    private FirebaseUser currentUser;
    

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

        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        currentUser= FirebaseAuth.getInstance().getCurrentUser();

        databaseReference= FirebaseDatabase.getInstance().getReference().child("Users");


    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap=googleMap;
        mMap.clear();
        mMap.setMyLocationEnabled(true);




        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mMap.clear();
                    for(DataSnapshot datasnap:dataSnapshot.getChildren()){
                        if(!currentUser.getUid().equals(datasnap.child("uid").getValue(String.class))) {
                            LatLng user = new LatLng(
                                    datasnap.child("latitude").getValue(Double.class),
                                    datasnap.child("longitude").getValue(Double.class)
                            );

                            mMap.addMarker(new MarkerOptions()
                                    .position(user)
                                    .title(dataSnapshot.child("name").getValue(String.class)).icon(
                                        BitmapDescriptorFactory.fromResource(R.drawable.car)));
                        }
                    }

            }

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

            }


        });
        

    }

   
}

1 Risposte

  • Re: Apertura APP show della mia posizione corrente

    Ho risolto così, due problemi. Il problema è che quando apro, noto al di sotto del mio Marker, il Marker che dovrebbero guardare gli altri Client.
    Ho aggiunto anche un set delle mie coordinate alla fine, così da tenerle aggiornate.

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
        private GoogleMap mMap;
        private DatabaseReference databaseReference;
        private FirebaseUser currentUser;
    
        Location mLocation;
        FusedLocationProviderClient fusedLocationProviderClient;
        private static final int Request_Code=101;
    
    
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Retrieve the content view that renders the map.
            setContentView(R.layout.activity_maps);
            currentUser= FirebaseAuth.getInstance().getCurrentUser();
            databaseReference= FirebaseDatabase.getInstance().getReference().child("Users");
    
            fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
            GetlastLocation();
    
        }
    
        private void GetlastLocation() {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
                return;
            }
    
            Task<Location> task=fusedLocationProviderClient.getLastLocation();
            task.addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if(location!=null){
                        mLocation=location;
                        Toast.makeText(getApplicationContext(),"CIAO"+mLocation.getLatitude()+" : "+mLocation.getLongitude(),Toast.LENGTH_SHORT).show();
                        SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
                                .findFragmentById(R.id.map);
                        mapFragment.getMapAsync(MapsActivity.this);
    
                    }
                }
            });
        }
    
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng latLng=new LatLng(mLocation.getLatitude(),mLocation.getLongitude());
            mMap=googleMap;
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,40));
            databaseReference.child(currentUser.getUid()).child("latitude").setValue(mLocation.getLatitude());
            databaseReference.child(currentUser.getUid()).child("longitude").setValue(mLocation.getLongitude());
    
    
    
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    mMap.clear();
                        for(DataSnapshot datasnap:dataSnapshot.getChildren()){
                            if(!currentUser.getUid().equals(datasnap.child("uid").getValue(String.class))) {
                                LatLng user = new LatLng(
                                        datasnap.child("latitude").getValue(Double.class),
                                        datasnap.child("longitude").getValue(Double.class)
                                );
    
                                mMap.addMarker(new MarkerOptions()
                                        .position(user)
                                        .title(dataSnapshot.child("name").getValue(String.class)).icon(
                                            BitmapDescriptorFactory.fromResource(R.drawable.car)));
                            }
                        }
                    mMap.addMarker(new MarkerOptions().position(latLng).title("You Are Here").icon(
                            BitmapDescriptorFactory.fromResource(R.drawable.automobile)));
                }
    
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
    
                }
            });
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch(requestCode){
                case Request_Code:
                    if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                        GetlastLocation();
                    break;
            }
        }
    }
Devi accedere o registrarti per scrivere nel forum
1 risposte