0

I’m trying to call the latitude and longitude to my google maps activity so it will display markers for its locations I’m using MVVM architecture with a room database using Kotlin, I have a JSON api with a list of lat and lng, stuck on the maps activity class part.

Essentially I’m trying to get the data from the api MVVM architecture , give it to the main activity and just pass the latlng and display it on google maps as a marker

Dtrex
  • 1
  • 2

1 Answers1

0

You just need to update a list of coordinates in the LiveData. In the Observer that you have in the activity, update the markers that you draw on the map whenever the list is updated.

Say you have this model for each coordinate, which you will use to store the results from the API call or Room database query:

data class LatLonModel(
        val lat: Double,
        val lon: Double
)

Then in the ViewModel, you have your LiveData:

var coordinates = MutableLiveData<List<LatLonModel>>()

Then in the Activity, you set up your ViewModel and Observer, so that whenever the coordinates LiveData is updated, you re-draw the current markers to the Google Map.

Set up the ViewModel:

private val viewModel: MyViewModel by viewModels()

Then set up the Observer in the onCreate() override:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //....

        viewModel.coordinates.observe(this, Observer {
            // Clear previous markers:
            mGoogleMap?.clear()

            // Place all current markers:
            it.forEach { latLonModel ->
                val latLng = LatLng(latLonModel.lat, latLonModel.lon)
                val markerOptions = MarkerOptions()
                markerOptions.position(latLng)
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))

                val marker = mGoogleMap?.addMarker(markerOptions)
            }
        }) 
}

Just to note, the mGoogleMap field is defined like this:

var mGoogleMap: GoogleMap? = null

For the full Activity class where you can integrate this functionality, see the answer here: https://stackoverflow.com/a/44993694/4409409

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137