Adding Multiple Markers from Firestore Database on Google Maps in Android Studio using Java

Viewed 510

I'm new to Android development and I wanted to ask how I would be able to add multiple markers to my application using the coordinates stored in Firebase. A screenshot of the Firebase is shown, but it helps me get only one marker for now. I want to get multiple markers by accessing the same document or suggestions that can help me manage places stored in firebase in a more organized way and display them on the map along with name and location. I've been able to retrieve on location, for now, screenshots of the app and firebase are attached.

enter image description here

enter image description here

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    private FusedLocationProviderClient mFusedLocationClient;
    //These Clusters were used to manage the marker Clusters that had images on maps too
    private ClusterManager mClusterManager;
    //Same is the case with these clusters
    private MyClusterManagerRenderer myClusterManagerRenderer;
    //Instantiating the Firestore Database
    FirebaseFirestore db;

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

        // initializing our firebase firestore.
        db = FirebaseFirestore.getInstance();

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //Getting the device location over here
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    private void addMapMarkers(){

    }




    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if(task.isSuccessful()){
                    Location location = task.getResult();

                }
            }
        });
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");

        // calling document reference class with on snap shot listener.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value != null && value.exists()) {
                    // below line is to create a geo point and we are getting
                    // geo point from firebase and setting to it.
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");

                    // getting latitude and longitude from geo point
                    // and setting it to our location.
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());

                    // adding marker to each location on google maps
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));

                    // below line is use to move camera.
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                } else {
                    Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });
        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
            } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));
    }
    //Getting the Users current Location
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}
1 Answers

To be able to get multiple markers from Firestore, you need to read all the documents that exist under the MapsData collection. This means that you need to create a reference that points exact to the collection and then perform a get() call:

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("MapsData").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

Your code adds a single marker because you are creating only a DocumentReference object that contains only a single GeoPoint object. If you need to read them in real-time, then you can listen for real-time updates.

Related