在同一地图上显示多个注册用户的位置(Android Studio,Firebase,Kotlin) [英] Show multiple registered user`s location on the same map (Android Studio, Firebase, Kotlin)

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

问题描述

因此我的应用程序在地图上显示了我的位置,并且还将纬度/经度保存到了Firebase中.看起来是这样的:

So my app shows my location on the map, and it also saves the latitude/longitude onto Firebase. This is how it looks like:

我的用户位置的当前路径仅为"/users/userlocation".但是,我想保存用户位置"在每个用户下方,那么我希望所有这些标记都显示在我已经在此处创建的同一张地图上:

The current path of my user location is just "/users/userlocation". However, I want to save "userlocation" under each user, then I want all these markers to be shown on the same map which I already created here:

MapsActivity:

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

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

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


                        if (location != null) {
                            val latLng = LatLng(location.latitude, location.longitude)
                            val markerOptions = MarkerOptions().position(latLng)
                            map.addMarker(markerOptions)
                            map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
                        }
                    }
                }
            }
        }

    @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()
    }
}

这是我尝试过的:

@Parcelize
class User(val uid: String, val username: String, val profileImageUrl: String, locationlogging: String): Parcelable {
  constructor() : this("", "", "", "")
} 

我添加了"locationlogging"作为我的User.kt文件中的字符串,但是在这里我可能完全错了.

I added "locationlogging" as a string in my User.kt file, but I might be completely wrong here.

我尝试将其添加到我的saveUserToFirebaseDatabase函数内的RegisterActivity中:

I tried to add this into my RegisterActivity, within my saveUserToFirebaseDatabase Function:

 // Save user to firebase database
 private fun saveUserToFirebaseDatabase(profileImageUrl: String) {
        val uid = FirebaseAuth.getInstance().uid ?: ""
        val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")
        val user = User(uid, username_edittext_register.text.toString(), profileImageUrl)
}

我不确定100%,但是我认为这是我应该实现用户位置的部分,因此应将其添加到所有注册的成员中,就像配置文件图像URL,uid和用户名一样.我尝试的任何操作都会给我带来错误.我会完全偏离轨道吗?如何将每个注册用户的位置添加到我的Firebase中,以同时在Google Map上显示所有位置?

I am not 100% sure, but I think this is the part where I should implement the user`s location, so it should be added to all registered members, the same way as profile image URL, uid, and username. Anything I try gives me errors. Am I completely off-track? How do I add the locations for each of the registered users into my firebase to show all of them at the same time on the Google Map?

推荐答案

您当前的位置路径是:

/users/userlocation

这似乎是不正确的,因为每个User对象都应该有自己的位置.为此,您可以采用以下三种方法之一:

Which doesn't seem to be correct, because every User object should have its own location. To achieve that, you can go ahead with one of the following three approaches:

Firebase-root
  |
  --- users
       |
       --- $uid
            |
            --- profileImageUrl: "https://..."
            |
            --- uid: "h9xZs...bV82"
            |
            --- username: "Bad Pug"
            |
            --- location
                  |
                  --- latitude: 53.37...
                  |
                  --- longitude: -0.90...

表示该位置"是包含纬度和经度的地图.第二种方法可能是直接在User对象下添加纬度和经度:

Meaning that "location" is a Map containing the latitude and longitude. The second approach might be to add both latitude and longitude directly under the User object:

Firebase-root
  |
  --- users
       |
       --- $uid
            |
            --- profileImageUrl: "https://..."
            |
            --- uid: "h9xZs...bV82"
            |
            --- username: "Bad Pug"
            |
            --- latitude: 53.37...
            |
            --- longitude: -0.90...

如果您考虑在某个时间点尝试使用 Cloud Firestore ,则可以请使用地理位置,因为它是支持的数据类型.您的Firestore模式可能如下所示:

If you consider at some point in time to try using Cloud Firestore, you can use a geographical point, as it's a supported data type. Your Firestore schema might look like this:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid (document)
            |
            --- profileImageUrl: "https://..."
            |
            --- uid: "h9xZs...bV82"
            |
            --- username: "Bad Pug"
            |
            --- geoPoint: [53.37...° N,  -0.90...° E]

解决此问题的关键是添加地图(对于第一个解决方案),两个新的double属性(对于第二个解决方案)或GeoPoint对象(对于第三种解决方案),并填充相应的纬度和经度值.将User对象写入数据库后,您将获得上面的一种架构.

The key to solving this issue is to add either a Map (for the first solution), two new double properties (for the second solution), or a GeoPoint object (for the third solution), and populate with the corresponding latitude and longitude values. Once you write the User object to the database, you'll have one of the schema from above.

在代码中,例如,要获取第二个示例中的纬度和经度,请使用以下代码行:

In code, to get for example the latitude and longitude in the second example, please use the following lines of code:

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

logcat中的结果将是:

The result in the logcat will be:

53.37..., -0.90...

这篇关于在同一地图上显示多个注册用户的位置(Android Studio,Firebase,Kotlin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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