【问题标题】:display variable name instead of value in foreach loop在 foreach 循环中显示变量名而不是值
【发布时间】:2020-03-05 20:58:48
【问题描述】:

您正在我的应用中使用地图。我必须在我的地图中添加多个标记。我已将所有标记放在 ArrayList 中。现在使用 foreach 循环放置标记。到这里为止,一切都运行良好。但我想给那个标记加上标题。并且该标题应该是我在数组列表中添加的变量名。 这是我的数组列表

 placeslist  = ArrayList<LatLng>()
            pietrasanta = getLocationFromAddress(this, "pietrasanta the italian resturant")
            Ikea_alexandra = getLocationFromAddress(this, "Ikea alexandra resturant,317")
            candlenut_resturant = getLocationFromAddress(this, "candlenut resturant,17A ")

            placeslist.add(pietrasanta )
            placeslist.add(Ikea_alexandra)
            placeslist.add(candlenut_resturant)

从此 getLocationFromAddress 方法获取 lnglat

 fun getLocationFromAddress(context: Context, strAddress: String): LatLng {
        val coder: Geocoder = Geocoder(context)
        val address1: List<Address>
        lateinit var p1: LatLng



        try {
            address1 = coder.getFromLocationName(strAddress, 5)
            if (address1 == null) {

            }
            val location: Address = address1.get(0)
            location.latitude
            location.latitude
            p1 = LatLng(location.latitude, location.longitude)


        } catch (e: Exception) {
            e.printStackTrace()
        }

        return p1
    }

现在在 foreach 循环的帮助下,我在 onMapReady() 中添加标记

  placeslist.forEach(){
            mMap.addMarker(MarkerOptions().position(it).title())    
        }

到这里一切都很好。当我试图添加 .title() 时,问题就出现了 在标题的地方,我想在 arraylist 中显示变量标签,而不是 pietrasanta、Ikea_alexandra、candlenut_resturant 和它们各自的标记的值。谁能帮助我如何将变量名添加为字符串而不是其值。

我试过这个mMap.addMarker(MarkerOptions().position(it).title(it.toString()))
但不是名称纬度和经度值显示为标题。

【问题讨论】:

    标签: android google-maps foreach


    【解决方案1】:

    不要使用 ArrayList,而是使用 HashMap :

    var placeslist : HashMap<String, LatLng> = HashMap<String, LatLng> ()
    
    placeslist.put("pietrasanta", getLocationFromAddress(this, "pietrasanta the italian 
    resturant"))
    placeslist.put("Ikea_alexandra", getLocationFromAddress(this, "Ikea alexandra 
    resturant,317"))
    placeslist.put("candlenut_resturant", getLocationFromAddress(this, "candlenut 
    resturant,17A "))
    

    用于检索数据:

    for(key in placeslist.keys){
            // here key will be your identifier (as you want variable name)
            // placeslist[key] will be you LatLng object for particular key
    }
    

    但是,不要在同一个 hashmap 中添加重复的键名。

    【讨论】:

    • 你能告诉我如何在添加标记中添加位置值 .for(key in placeslist){ mMap.addMarker( MarkerOptions().position(placeslist.values).title(key)) } ..这样做但 position() 显示错误。
    • 这样完成 mMap.addMarker( MarkerOptions().position(placeslist.getValue(key)).title(key)) 非常感谢。
    猜你喜欢
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多