Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to Add Dynamic Markers in Google Maps with Firebase Firstore?

Adding dynamic markers to Google Maps using data from Firebase Firestore involves a series of steps:

  1. Setting Up Google Maps:

    Before integrating Firestore, first, ensure that you have set up Google Maps in your Android project.

  2. Integrate Firebase and Firestore:

    If you haven't already integrated Firestore in your project:

    • Go to the Firebase Console and set up a new project or use an existing one.
    • Integrate Firebase with your Android project.
    • Add Firestore dependencies to your app's build.gradle:
      implementation 'com.google.firebase:firebase-firestore:21.7.0' // use the latest version
      
  3. Structure Your Firestore Data:

    Let's assume your Firestore collection is structured as:

    Collection "markers" {
        Document "ID" {
            "name": "Sample Marker",
            "latitude": xx.xxxx,
            "longitude": xx.xxxx
        }
        ... other documents ...
    }
    
  4. Fetch Data from Firestore and Add to Google Maps:

    In your activity or fragment:

    val db = FirebaseFirestore.getInstance()
    val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync { googleMap ->
        // Fetch markers from Firestore
        db.collection("markers").get().addOnSuccessListener { documents ->
            for (document in documents) {
                val latitude = document.getDouble("latitude") ?: continue
                val longitude = document.getDouble("longitude") ?: continue
                val name = document.getString("name") ?: "Default Name"
    
                // Create a LatLng object with the fetched coordinates
                val location = LatLng(latitude, longitude)
    
                // Add the marker to Google Maps
                googleMap.addMarker(MarkerOptions().position(location).title(name))
            }
        }
    }
    
  5. Real-time Updates (Optional):

    If you want the markers to be updated in real-time whenever there's a change in Firestore, you can use addSnapshotListener:

    mapFragment.getMapAsync { googleMap ->
        db.collection("markers")
        .addSnapshotListener { snapshots, error ->
            if (error != null) {
                Log.w(TAG, "Listen failed.", error)
                return@addSnapshotListener
            }
    
            // Clear existing markers
            googleMap.clear()
    
            for (document in snapshots!!) {
                val latitude = document.getDouble("latitude") ?: continue
                val longitude = document.getDouble("longitude") ?: continue
                val name = document.getString("name") ?: "Default Name"
                
                // Create a LatLng object with the fetched coordinates
                val location = LatLng(latitude, longitude)
    
                // Add the marker to Google Maps
                googleMap.addMarker(MarkerOptions().position(location).title(name))
            }
        }
    }
    

That's it! Now, whenever you add a new document to the Firestore "markers" collection, it'll be displayed as a marker on your Google Map.

  1. Adding dynamic markers from Firestore to Google Maps:

    • Description: Retrieve geolocation data from Firestore and add dynamic markers to Google Maps.
    • Code:
      val db = FirebaseFirestore.getInstance()
      val markersCollection = db.collection("markers")
      
      markersCollection.get().addOnSuccessListener { querySnapshot ->
          for (document in querySnapshot.documents) {
              val latitude = document.getDouble("latitude")
              val longitude = document.getDouble("longitude")
      
              // Add a marker to Google Maps
              val marker = MarkerOptions()
                  .position(LatLng(latitude!!, longitude!!))
                  .title("Marker Title")
              googleMap.addMarker(marker)
          }
      }
      
  2. Real-time updates for markers in Google Maps with Firestore:

    • Description: Implement real-time updates for dynamic markers as Firestore data changes.
    • Code:
      val markersCollection = db.collection("markers")
      
      markersCollection.addSnapshotListener { querySnapshot, exception ->
          if (exception != null) {
              // Handle error
              return@addSnapshotListener
          }
      
          for (documentChange in querySnapshot!!.documentChanges) {
              val latitude = documentChange.document.getDouble("latitude")
              val longitude = documentChange.document.getDouble("longitude")
      
              // Update or add marker based on change type
              // ...
          }
      }
      
  3. Customizing marker appearance with Firestore data in Android:

    • Description: Customize the appearance of markers based on Firestore data, such as changing colors or icons.
    • Code:
      val markerColor = document.getString("markerColor")
      val markerIconUrl = document.getString("markerIconUrl")
      
      val marker = MarkerOptions()
          .position(LatLng(latitude!!, longitude!!))
          .title("Marker Title")
          .icon(BitmapDescriptorFactory.defaultMarker(getMarkerColor(markerColor)))
          // .icon(BitmapDescriptorFactory.fromUrl(markerIconUrl)) // For custom icons
      googleMap.addMarker(marker)