在地图上同时显示多个用户的位置(科特林,Firebase实时数据库) [英] Show multiple user`s location at the same time on a map (Kotlin, Firebase Realtime Database)

查看:67
本文介绍了在地图上同时显示多个用户的位置(科特林,Firebase实时数据库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题反映出先前的问题:

我想要用户位置"显示在我的每个注册用户下方,因此所有注册用户的位置都将在我的Google地图上显示为标记.

这是我的MapsActivity:

  class MapsActivity:AppCompatActivity(),OnMapReadyCallback {伴随对象{var currentUser:用户?=空val TAG ="MapsActivity";}私人lateinit var地图:GoogleMap私有值LOCATION_PERMISSION_REQUEST = 1私有lateinit var fusedLocationClient:FusedLocationProviderClient私人lateinit var locationRequest:LocationRequest私人lateinit var locationCallback:LocationCallback私人乐趣getLocationAccess(){如果(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){map.isMyLocationEnabled = truegetLocationUpdates()startLocationUpdates()}别的ActivityCompat.requestPermissions(this,arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),LOCATION_PERMISSION_REQUEST)}私人乐趣getLocationUpdates(){locationRequest = LocationRequest()locationRequest.interval = 30000locationRequest.fastestInterval = 20000locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACYlocationCallback = object:LocationCallback(){重写fun onLocationResult(locationResult:LocationResult){如果(locationResult.locations.isNotEmpty()){val location = locationResult.lastLocation//val uid = FirebaseAuth.getInstance().currentUser?.uid//val rootRef = FirebaseFirestore.getInstance()//val usersRef = rootRef.collection("users")//val uidRef = uid?.let {usersRef.document(it)}//如果(uidRef!= null){//uidRef.get()//.addOnSuccessListener {document->//if(document!= null){//val latitude = document.getDouble("latitude")//val经度= document.getDouble("longitude")//Log.d(TAG," ;," + location.latitude + location.longitude)//                                   } 别的 {//Log.d(TAG,没有这样的文档")//}//}//.addOnFailureListener {例外->//Log.d(TAG,由于失败而失败",例外)//}//}lateinit var databaseRef:数据库参考databaseRef = Firebase.database.referenceval locationlogging = LocationLogging(location.latitude,location.longitude)databaseRef.child("/userlocation").setValue(locationlogging).addOnSuccessListener {Toast.makeText(applicationContext,写入数据库的位置",Toast.LENGTH_LONG).show()}.addOnFailureListener {Toast.makeText(applicationContext,将您的位置写入数据库时​​发生错误",Toast.LENGTH_LONG).show()}}}}}@SuppressLint("MissingPermission")私人娱乐startLocationUpdates(){fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,null)}@SuppressLint("MissingPermission")重写fun onRequestPermissionsResult(requestCode:Int,权限:Array< String> ;, grantResults:IntArray){如果(requestCode == LOCATION_PERMISSION_REQUEST){如果(grantResults.contains(PackageManager.PERMISSION_GRANTED)){map.isMyLocationEnabled = true} else {Toast.makeText(this,用户未授予位置访问权限",Toast.LENGTH_LONG).show()结束()}}}重写fun onCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_maps)//获取SupportMapFragment并在准备使用地图时得到通知.val mapFragment = supportFragmentManager.findFragmentById(R.id.map)作为SupportMapFragmentmapFragment.getMapAsync(this)fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)}覆盖乐趣onMapReady(googleMap:GoogleMap){地图= googleMapgetLocationAccess()}覆盖fun onCreateOptionsMenu(菜单:菜单?):布尔值{menuInflater.inflate(R.menu.nav_menu_map,菜单)返回super.onCreateOptionsMenu(菜单)} 

我注释掉了一些代码,因为我无法正确实现它.运行代码时,纬度和经度出现在Logcat中,但是在我的实时数据库中,它清除了/users下的所有数据,并由纬度和经度代替.

这是我的位置记录:

 导入com.google.firebase.database.IgnoreExtraProperties@IgnoreExtraProperties数据类LocationLogging(var Latitude:加倍?= 0.0,var经度:双倍?= 0.0) 

我正在寻找一种简单的方法,将坐标放入每个注册用户的Firebase实时数据库中,并同时在地图上显示所有位置.

解决方案

您可以使用firebase auth SDK获取当前用户,并更改保存数据的路径以将其保存在用户路径下.您需要更改代码的这一部分:

 <代码>FirebaseUser用户= FirebaseAuth.getInstance().getCurrentUser();lateinit var databaseRef:数据库参考databaseRef = Firebase.database.referenceval locationlogging = LocationLogging(location.latitude,location.longitude)databaseRef.child("users").child(user.getUid()).child("userlocation").setValue(locationlogging).addOnSuccessListener {Toast.makeText(applicationContext,写入数据库的位置",Toast.LENGTH_LONG).show()}.addOnFailureListener {Toast.makeText(applicationContext,将您的位置写入数据库时​​发生错误",Toast.LENGTH_LONG).show()} 

This question reflects back to a previous question: Show multiple registered user`s location on the same map (Android Studio, Firebase, Kotlin)

My main problem is that I have created a chatting app in Android Studio, and also added a map activity, using Google Api. I am using Firebase Realtime Database, and this is how my tree currently looks like:

I want the "userlocation" appear under each of my registered user, so all registered user`s location will will appear on my Google Map as a marker.

Here is my MapsActivity:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    companion object {
        var currentUser: User? = null
        val TAG = "MapsActivity"
    }



    private lateinit var map: GoogleMap
    private val LOCATION_PERMISSION_REQUEST = 1
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback


    private fun getLocationAccess() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            map.isMyLocationEnabled = true
            getLocationUpdates()
            startLocationUpdates()
        }
        else
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST)


    }



    private fun getLocationUpdates() {
        locationRequest = LocationRequest()
        locationRequest.interval = 30000
        locationRequest.fastestInterval = 20000
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                if (locationResult.locations.isNotEmpty()) {
                    val location = locationResult.lastLocation




//                    val uid = FirebaseAuth.getInstance().currentUser?.uid
//                    val rootRef =  FirebaseFirestore.getInstance()
//                    val usersRef = rootRef.collection("users")
//                    val uidRef = uid?.let { usersRef.document(it) }
//                    if (uidRef != null) {
//                        uidRef.get()
//                                .addOnSuccessListener { document ->
//                                    if (document != null) {
//                                        val latitude = document.getDouble("latitude")
//                                        val longitude = document.getDouble("longitude")
//                                        Log.d(TAG, ", " + location.latitude + location.longitude)
//                                    } else {
//                                        Log.d(TAG, "No such document")
//                                    }
//                                }
//                                .addOnFailureListener { exception ->
//                                    Log.d(TAG, "get failed with ", exception)
//                                }
//                    }


                    lateinit var databaseRef: DatabaseReference
                    databaseRef = Firebase.database.reference
                    val locationlogging = LocationLogging(location.latitude, location.longitude)
                    databaseRef.child("/userlocation").setValue(locationlogging)

                        .addOnSuccessListener {
                            Toast.makeText(applicationContext, "Locations written into the database", Toast.LENGTH_LONG).show()
                        }
                        .addOnFailureListener {
                            Toast.makeText(applicationContext, "Error occured while writing your location to the database", Toast.LENGTH_LONG).show()
                        }

                }

            }
        }
    }




    @SuppressLint("MissingPermission")
    private fun startLocationUpdates() {
        fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback, null)
    }


    @SuppressLint("MissingPermission")
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == LOCATION_PERMISSION_REQUEST) {
            if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
                map.isMyLocationEnabled = true
            } else { Toast.makeText(this, "User has not granted location access permission", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }


    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)
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }


    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        getLocationAccess()
    }




    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.nav_menu_map, menu)
        return super.onCreateOptionsMenu(menu)
    }

I commented out some of the codes as I wasn`t able to implement it properly. When I ran the code, the latitude and longitude appeared in my Logcat, but in my Realtime database, it wiped out all my data under /users and it was replaced by the latitude and longitude.

Here is my LocationLogging:


import com.google.firebase.database.IgnoreExtraProperties

@IgnoreExtraProperties

data class LocationLogging(
    var Latitude: Double? = 0.0,
    var Longitude: Double? = 0.0
)

I am looking to find an easy way, which puts the coordinates into my Firebase Realtime Database under each of my registered users, and show all locations on the map at the same time.

解决方案

You can get the current user with the firebase auth SDK and change the path where you save the data to save it under the user path. You would need to change this part of your code:


FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
 lateinit var databaseRef: DatabaseReference
                    databaseRef = Firebase.database.reference
                    val locationlogging = LocationLogging(location.latitude, location.longitude)
                    databaseRef.child("users").child(user.getUid()).child("userlocation").setValue(locationlogging)

                        .addOnSuccessListener {
                            Toast.makeText(applicationContext, "Locations written into the database", Toast.LENGTH_LONG).show()
                        }
                        .addOnFailureListener {
                            Toast.makeText(applicationContext, "Error occured while writing your location to the database", Toast.LENGTH_LONG).show()
                        }

这篇关于在地图上同时显示多个用户的位置(科特林,Firebase实时数据库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆