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