How to collaborate mapbox markers and firebase realtime data? - kotlin

I've been trying to figure out how to connect firebase and mapbox together since I am new and trying to learn more about it. Is there any way I can do so the markers in the mapbox will follow the firebase realtime data?
Below is the code written in kotlin.
I tried searching around but it seems like there are rare guides for mapbox.
package com.example.s_tore
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.mapbox.geojson.Point.fromLngLat
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.plugin.annotation.AnnotationConfig
import com.mapbox.maps.plugin.annotation.AnnotationPlugin
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationManager
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager
class smap : AppCompatActivity() {
var mapView: MapView? = null
private lateinit var database: DatabaseReference
var annotationApi : AnnotationPlugin? = null
lateinit var annotationConfig: AnnotationConfig
var layer1DD = "map_annotation"
var pointAnnotationManager : PointAnnotationManager? = null
var markerlist : ArrayList<PointAnnotationOptions> = ArrayList()
var latitudeList : ArrayList<Double> = ArrayList()
var longitudeList : ArrayList<Double> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_smap)
mapView = findViewById(R.id.maps)
createDummyAList()
mapView?.getMapboxMap()!!.loadStyleUri(
Style.MAPBOX_STREETS,
object : Style.OnStyleLoaded{
override fun onStyleLoaded(style: Style) {
ZoomCamera()
annotationApi = mapView?.annotations
annotationConfig = AnnotationConfig(
layerId = layer1DD
)
pointAnnotationManager = annotationApi?.createPointAnnotationManager(annotationConfig)
createMarkerOnMap()
}
}
)
}
private fun ZoomCamera(){
mapView!!.getMapboxMap().setCamera(
CameraOptions.Builder().center(fromLngLat(122.061213, 6.913414))
.zoom(17.0)
.build())
}
private fun createDummyAList(){
latitudeList.add(6.914586)
longitudeList.add(122.061069)
}
private fun createMarkerOnMap(){
val bitmap = convertDrawabletoBitMap(AppCompatResources.getDrawable(this, R.drawable.locationmark))
for (i in 0 until 1000){
val pointAnnotationOptions : PointAnnotationOptions = PointAnnotationOptions()
.withPoint(fromLngLat(longitudeList.get(i),latitudeList.get(i)))
.withIconImage(bitmap!!)
markerlist.add(pointAnnotationOptions)
}
pointAnnotationManager?.create(markerlist)
}
private fun convertDrawabletoBitMap(sourceDrawable: Drawable?):Bitmap{
return if(sourceDrawable is BitmapDrawable){
sourceDrawable.bitmap
}else{
val constatState = sourceDrawable?.constantState
val drawable = constatState?.newDrawable()?.mutate()
val bitmap : Bitmap = Bitmap.createBitmap(
drawable!!.intrinsicWidth,drawable!!.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
bitmap
}
}
}

Related

How to send a variable to an Adapter to send it through an Intent to another activity?

I have an adapter for my RecyclerView where I program that when I click on the element (of my RecyclerView) it executes an Intent with a putExtra to take me to another activity, the variable that contains my putExtra comes from the element that I clicked, but now I need to add a More variable that comes from the activity. The issue is that I don't know how to send it from the adapter.
this is my adapter.
package com.example.atipicoapp
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.list_item.view.*
class MyAdapter(private val platoList : ArrayList<Plato>
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.MyViewHolder {
val itemView =
LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
itemView.platoTouch.setOnClickListener(View.OnClickListener { v: View ->
})
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyAdapter.MyViewHolder, position: Int) {
val plato: Plato = platoList[position]
holder.platoName.text = plato.platoName
holder.platoDescription.text = plato.platoDescription
holder.platoPrecio.text = plato.platoPrecio.toString()
holder.platoCantidad.text = plato.platoCantidad.toString()
when(holder){
is MyViewHolder -> {
holder.bind(platoList[position])
}
}
}
override fun getItemCount(): Int {
return platoList.size
}
public class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val platoName: TextView = itemView.findViewById(R.id.platoNombre)
val platoDescription: TextView = itemView.findViewById(R.id.platoDescripcion)
val platoPrecio: TextView = itemView.findViewById(R.id.platoPrecio)
val platoTouch: LinearLayout = itemView.findViewById(R.id.platoTouch)
val platoCantidad: TextView = itemView.findViewById(R.id.platoCant)
private val mActivity = itemView.context as Activity
private val intent = Intent(mActivity,SlotActivity::class.java)
fun bind(plato: Plato){
platoTouch.setOnClickListener{
intent.putExtra("id", platoName.text.toString())
mActivity.startActivity(intent)
}
}
}
}
And this is my Activity which contains my RecyclerView and the variable I want to send.
package com.example.atipicoapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_menu_atipico.*
class MenuAtipicoActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var platoArrayList: ArrayList<Plato>
private lateinit var myAdapter: MyAdapter
private lateinit var db: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu_atipico)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
platoArrayList = arrayListOf()
myAdapter = MyAdapter(platoArrayList)
recyclerView.adapter = myAdapter
pedidoId = intent.extras?.getString("pedidoId") //This is the variable I need to send
EventChangeListener()
Setup()
}
private fun EventChangeListener() {
db = FirebaseFirestore.getInstance()
db.collection("Platos").addSnapshotListener(object : EventListener<QuerySnapshot> {
override fun onEvent(
value: QuerySnapshot?,
error: FirebaseFirestoreException?
) {
if (error != null) {
Log.e("Firestore Error", error.message.toString())
return
}
for (dc: DocumentChange in value?.documentChanges!!) {
if (dc.type == DocumentChange.Type.ADDED) {
platoArrayList.add(dc.document.toObject(Plato::class.java))
}
}
myAdapter.notifyDataSetChanged()
}
})
}
private fun Setup() {
botonAceptar.setOnClickListener {
val SlotIntent = Intent(this, SlotActivity::class.java).apply {
}
startActivity(SlotIntent)
}
}
}
How can I send the variable if the Intent is executed from the Adapter?
Or... If it is not recommended to send intent from my Adapter, how can I send them from the activity?
Knowing that I have to carry a variable that is in the item of the RecyclerView.
Thanks for your help <3
Firstly, create a MyAdapter constructor where you pass arrayList as well as pedidoId like, your MyAdapter should be something like below:
MyAdapter.class
class MyAdapter(private val platoList : ArrayList<Plato>, val pedidoId:String
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
........
.....
....
//in your bind(..) method
fun bind(plato: Plato){
platoTouch.setOnClickListener{
intent.putExtra("id", platoName.text.toString())
intent.putExtra("pedidoId", pedidoId)
mActivity.startActivity(intent)
}
}
}
And, in your MenuAtipicoActivity you need to do something like:
MenuAtipicoActivity
class MenuAtipicoActivity : AppCompatActivity() {
...............
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu_atipico)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
platoArrayList = arrayListOf()
pedidoId = intent.extras?.getString("pedidoId") //This is the variable I need to send
myAdapter = MyAdapter(platoArrayList,pedidoId)
recyclerView.adapter = myAdapter
EventChangeListener()
Setup()
}
..........
........
}

Display asset text file in Composable function using Kotlin Jetpack Compose

I'm trying to read a text file using Kotlin from my Assets folder and display it to a Compose text widget. Android Studio Arctic Fox 2020.3
The following code runs successfully and displays the text file to the Output console, however I can't figure out how to get the text file and pass it to a Compose text widget.
You'll notice that I have 2 text() calls inside ReadDataFile(). The first text() is outside of try{} and it works fine, but the text() inside the try{} causes an error: "Try catch is not supported around composable function invocations"
How can I make this work?
Thanks!
package com.learning.kotlinreadfile
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import com.learning.kotlinreadfile.ui.theme.KotlinReadFileTheme
import java.io.InputStream
import java.io.IOException
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KotlinReadFileTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
ReadDataFile()
}
}
}
}
}
#Composable
fun ReadDataFile() {
println("Read Data File")
Text("Read Data File")
val context = LocalContext.current
try {
val inputStream: InputStream = context.assets.open("data.txt")
val size: Int = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
var string = String(buffer)
println(string)
//Text(string) // ERROR: Try catch is not supported around composable function invocations
} catch (e: IOException) {
e.printStackTrace()
println("Error")
}
}
Caution
File read (I/O) operations can be long, so it is not recommended to use the UI scope to read files. But that's not what's causing the problem, I'm just warning you that if it reads very large files, it can make your app crash because it does a very long processing in the UI thread. I recommend checking this link if you're not familiar with this type of problem.
Problem solving following best practices
Fortunately Jetpack compose works very well with reactive programming, so we can take advantage of that to write reactive code that doesn't face the aforementioned problems.
I made an example very similar to yours, I hope you can understand:
UiState file
As stated earlier, reading a file can be a long process, so let's imagine 3 possible states, "loading", "message successful" and "error". In the case of "successful message" we will have a possibly null string that will no longer be null when the message is actually read from the txt file:
package com.example.kotlinreadfile
data class UiState(
val isLoading: Boolean,
val isOnError: Boolean,
val fileMessage: String?
)
MainActivity.kt file
Here will be just our implementation of the UI, in your case the text messages arranged in the application. As soon as we want to read these messages on the screen we will make a request to our ViewModel:
package com.example.kotlinreadfile
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.*
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.kotlinreadfile.ui.theme.KotlinReadFileTheme
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KotlinReadFileTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
val context = LocalContext.current
viewModel.loadData(context)
ScreenContent(viewModel.uiState.value)
}
}
}
}
#Composable
fun ScreenContent(uiState: UiState) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "Read Data File")
Spacer(modifier = Modifier.height(8.dp))
when {
uiState.isLoading -> CircularProgressIndicator()
uiState.isOnError -> Text(text = "Error when try load data from txt file")
else -> Text(text = "${uiState.fileMessage}")
}
}
}
}
MainViewModel.kt file
If you are unfamiliar with the ViewModel class I recommend this official documentation link.
Here we will focus on "our business rule", what we will actually do to get the data. Since we are dealing with an input/output (I/O) operation we will do this in an appropriate scope using viewModelScope.launch(Dispatchers.IO):
package com.example.kotlinreadfile
import android.content.Context
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream
class MainViewModel : ViewModel() {
private val _uiState = mutableStateOf(
UiState(
isLoading = true,
isOnError = false,
fileMessage = null
)
)
val uiState: State<UiState> = _uiState
fun loadData(context: Context) {
viewModelScope.launch(Dispatchers.IO) {
try {
val inputStream: InputStream = context.assets.open("data.txt")
val size: Int = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
val string = String(buffer)
launch(Dispatchers.Main) {
_uiState.value = uiState.value.copy(
isLoading = false,
isOnError = false,
fileMessage = string
)
}
} catch (e: IOException) {
e.printStackTrace()
launch(Dispatchers.Main) {
_uiState.value = uiState.value.copy(
isLoading = false,
isOnError = true,
fileMessage = null
)
}
}
}
}
}
jetpack compose by state refresh, please try
#Preview
#Composable
fun ReadDataFile() {
var dataText by remember {
mutableStateOf("asd")
}
println("Read Data File")
Column {
Text("Read Data File")
Text(dataText)
}
val context = LocalContext.current
LaunchedEffect(true) {
kotlin.runCatching {
val inputStream: InputStream = context.assets.open("data.txt")
val size: Int = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
String(buffer)
}.onSuccess {
it.logE()
dataText = it
}.onFailure {
dataText = "error"
}
}
}

ListView var not found

I followed a tutorial on how to do a listview in kotlin and I encountered this problem. I'm new to Kotlin and I don't understand what are the getters and setters for my activity. From what I read it should be put automatically.
private lateinit var listView ListView
Property getter or setter expected
All code:
package com.example.librariasemnelor;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button
import android.widget.ListView;
private lateinit var listView ListView
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val actionBar = supportActionBar
if(actionBar != null){
actionBar.title = "Meniu principal"
actionBar.setDisplayHomeAsUpEnabled(true)
}
listView = findViewById<ListView>(R.id.recipe_list_view)
// 1
val recipeList = Recipe.getRecipesFromFile("recipes.json", this)
// 2
val listItems = arrayOfNulls<String>(recipeList.size)
// 3
for (i in 0 until recipeList.size) {
val recipe = recipeList[i]
listItems[i] = recipe.title
}
// 4
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems)
listView.adapter = adapter
}
}
private lateinit ... should be placed inside the class block.
And : must be added just after listView.
class SecondActivity : AppCompatActivity() {
private lateinit var listView: ListView
override fun onCreate(savedInstanceState: Bundle?) {
...
}
...
}

Add button in recyclerview to edit or delete data from realtime database

i'm a beginner in programming so forgive me if my code is messy. I need some help to complete my program.
I'm using recyclerview to retrieve some data from realtime database and i want to add edit and delete button in the recyclerview to edit and delete some data.
I already create the button in the xml file, i just don't know how to code the button. I already tried some tutorial from youtube and refer to some code in some others post on stack overflow but most of the time the code will either give me an error or the button will not do anything. I've included my code and database structure below:
DoctorViewAdapter.kt
package com.example.patientmonitor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.util.ArrayList
import kotlin.concurrent.fixedRateTimer
class DoctorViewAdapter(private val patientList : ArrayList<doctorViewPatient>) : RecyclerView.Adapter<DoctorViewAdapter.DoctorViewHolder>() {
//WebView
private lateinit var pulseGraph: WebView
private lateinit var temperatureGraph: WebView
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoctorViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.patient_item,parent,false)
return DoctorViewHolder(itemView)
pulseGraph.webViewClient = WebViewClient()
temperatureGraph.webViewClient = WebViewClient()
pulseGraph.settings.javaScriptEnabled = true
temperatureGraph.settings.javaScriptEnabled = true
pulseGraph.settings.builtInZoomControls = true
temperatureGraph.settings.builtInZoomControls = true
}
override fun onBindViewHolder(holder: DoctorViewHolder, position: Int) {
val currentitem = patientList[position]
holder.userID.text = currentitem.userID
holder.fullName.text = currentitem.fullName
holder.userEmail.text = currentitem.email
holder.phoneNumber.text = currentitem.phoneNumber
var pulseValue = "null"
var temperatureValue = "null"
//get pulse value from thingspeak and set to text view
val pulsequeue = Volley.newRequestQueue(holder.pulseValue.context)
val temperaturequeue = Volley.newRequestQueue(holder.temperatureValue.context)
val pulseRequest = StringRequest(Request.Method.GET, currentitem.pulseValue as String?,
Response.Listener<String> { response ->
pulseValue = response
holder.pulseValue.text = pulseValue
}, Response.ErrorListener {
// didn't work
})
//get temperature value from thingspeak and set to text view
val tempRequest = StringRequest(Request.Method.GET, currentitem.temperatureValue as String?,
Response.Listener<String> { response ->
temperatureValue = response
holder.temperatureValue.text = temperatureValue
}, Response.ErrorListener {
// didn't work
})
//get thingspeak data every 1 second
fixedRateTimer("timer", false, 0L, 1000) {
pulsequeue.add(pulseRequest)
temperaturequeue.add(tempRequest)
}
}
override fun getItemCount(): Int {
return patientList.size
}
class DoctorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val userID : TextView = itemView.findViewById(R.id.tvUserID)
val fullName : TextView = itemView.findViewById(R.id.tvFullName)
val userEmail : TextView = itemView.findViewById(R.id.tvEmail)
val phoneNumber : TextView = itemView.findViewById(R.id.tvPhoneNumber)
val pulseValue : TextView = itemView.findViewById(R.id.tvPulseValue)
val temperatureValue : TextView = itemView.findViewById(R.id.tvTemperatureValue)
}
}
PatientlistActivity.kt
package com.example.patientmonitor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.database.*
class PatientListActivity : AppCompatActivity() {
private lateinit var dbref : DatabaseReference
private lateinit var userRecyclerview : RecyclerView
private lateinit var userArrayList : ArrayList<doctorViewPatient>
private lateinit var viewPatientBtn : FloatingActionButton
private lateinit var doctorViewAdapter : DoctorViewAdapter
//ActionBar
private lateinit var actionBar: ActionBar
//WebView
private lateinit var pulseView: WebView
private lateinit var tempView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_patient_list)
//configure Actionbar //enable back button
actionBar = supportActionBar!!
actionBar.title = "View Patients"
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setDisplayShowHomeEnabled(true)
userRecyclerview = findViewById(R.id.patientList)
userRecyclerview.layoutManager = LinearLayoutManager(this)
userRecyclerview.setHasFixedSize(true)
userArrayList = arrayListOf<doctorViewPatient>()
getUserData()
}
private fun getUserData() {
//get intent
val assignedDoctor = intent.getStringExtra("doctorID")
val currentUserAccess = intent.getStringExtra("currentUserAccess")
dbref = FirebaseDatabase.getInstance().getReference("Users")
dbref.orderByChild("assignedDoctor").equalTo(assignedDoctor).addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (userSnapshot in snapshot.children){
val user = userSnapshot.getValue(doctorViewPatient::class.java)
userArrayList.add(user!!)
}
userRecyclerview.adapter = DoctorViewAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
This is my data class
doctorViewPatient.kt
data class doctorViewPatient(val userID : String? =null,
val fullName : String? =null,
val email : String? =null,
val phoneNumber : String? =null,
val pulseValue : String? = null,
val temperatureValue : String? = null)
This is my Realtime Database Structure

Add markers to a map with Firebase

I want to make an application with Kotlin and Google Maps in which the user can add markers on the Google Map and that these markers are sent to Firebase and other users can see those same markers on the map.
This is what I have done but it is not working well for me.
package com.racrapa.displayinglocationapp
import android.content.ContentValues
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.database.*
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
private const val TAG = "MapsActivity"
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
public lateinit var databaseRef: DatabaseReference
private lateinit var database: DatabaseReference
private var markers: MutableList<Marker> = mutableListOf()
private var postListener: ValueEventListener? = null
var mDatabase: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
databaseRef = Firebase.database.reference
mDatabase = FirebaseDatabase.getInstance().reference.child("userlocation")
database = Firebase.database.reference
}
This is to get the data from Firebase
public override fun onStart() {
super.onStart()
var postListener: ValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val locationlogging = dataSnapshot.child("userlocation").getValue(LocationLogging::class.java)
var driverLat=locationlogging?.Latitude
var driverLong=locationlogging?.Longitude
if (driverLat != null && driverLong != null) {
val driverLoc = LatLng(driverLat, driverLong)
val markerOptions = MarkerOptions().position(driverLoc).title("Driver")
mMap.addMarker(markerOptions)
Toast.makeText(applicationContext, "Locations accessed from the database", Toast.LENGTH_LONG).show()
}
}
}
override fun onCancelled(error: DatabaseError) {}
}
databaseRef.addValueEventListener(postListener)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.setOnMapLongClickListener { latLng ->
Log.i(TAG, "onMapLongClickListener")
setMapLongClick(latLng)
}
}
This is the function of sending coordinates to Firebase
private fun setMapLongClick(latLng: LatLng) {
if (latLng != null) {
Log.e("Latitude: ", latLng.latitude.toString() + "longitude: " + latLng.longitude)
val latlang: MutableMap<String, Double> = HashMap()
latlang["latitude"] = latLng.latitude
latlang["longitude"] = latLng.longitude
mDatabase!!.child("userlocation").push().setValue(latlang)
onStart()
}
}
}