我有一个带有Coordinate(latitude,longitude)
数据类的listof()变量,例如,我是如何初始化它的:
var coordinate = listof<Coordinate>()
字符串
我想通过从Firebase数据库中检索纬度和经度来为多边形的每个标记添加纬度和经度,例如:
val databaseReference = FirebaseDatabase.getInstance().getReference("polygon").child("coordinate")
databaseReference.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val numberOfCoor = snapshot.childrenCount.toInt()
var i = 1
for (n in i until numberOfCoor + 1) {
val latitude = snapshot.child("coordinate$i")
.child("latitude").getValue().toString().toDouble()
val longitude = snapshot.child("coordinate$i")
.child("longitude").getValue().toString().toDouble()
coordinate.plus(Coordinate(longitude, latitude))
}
}
override fun onCancelled(error: DatabaseError) {
}
})
型
所以从上面的代码中可以看出,我用coordinate.plus(Coordinate(longitude, latitude))
添加了每个经纬度
但是当我下载这个GeoJSON文件时,坐标没有纬度和经度。
那么,如何在Kotlin中向listof()函数添加项呢?
谢谢
2条答案
按热度按时间qfe3c7zg1#
listOf
返回不可变的List<out Coordinate>
为了能够向列表中添加项,可以使用
mutableListOf<Coordinate>
示例化它iqxoj9l92#
.plus
方法不会修改原始列表。或者您可以使用.add
。使用
mutablelist
是一个很好的实践。你可以添加和删除元素。字符串