【问题标题】:How do I add map markers to a separate class file?如何将地图标记添加到单独的类文件中?
【发布时间】:2021-10-03 07:01:55
【问题描述】:

在 android studio 中,我创建了一张带有数百个标记的地图。我想将它们分成单独的类并将它们放在一个单独的包中,这样我的主代码中就没有一个庞大的标记列表。有没有办法做到这一点?我正在使用 Kotlin。

【问题讨论】:

    标签: android-studio google-maps kotlin


    【解决方案1】:

    所以我认为你想说的是。 有一个 Activity,比如说 MainActivity,里面有地图,上面有大约 200 个标记。

    所有这些都是单独初始化和分配的,您希望将它们全部组合在一起,以便您只需搜索一个就可以使用它们。

    如果是这样的话,我的建议是。

    创建一个单独的数据类来存储标记和与之相关的其他数据。

    data class MarkerInfo(
      //marker ID
      val id:Int,
      //marker Data
      val markerData:Marker,
      //other Data
      var otherData:String
    )
    

    现在开始存储和访问数据。

    class MainActivity(){
    
      //at the top level, inside Activity
      // This will create an empty list of Marker Info
      var markerData = mutableListOf<MarkerInfo>()
    
      //Now take any function, let's say x
      private fun x(){
      //Mark a Marker on Map and assign it to a variable.
      val markerA : Marker = map.addMarker( MarkerOptions.position(somePosition))
    
      //we assign a function with id and other relevant data
      val x= markerData.size
      
      //store data in list
      markerData.add(MarkerInfo(x, markerA, "This is a very useful marker"))
     }
    }
    
    //now to access that marker.
    //let's say there is a function named y.
    private fun y(){
      //say we want to access the first marker
      //there are two ways to do so.
    
      //first method: you know some data which is already in there let's say we know id
      for(i in markerData){
      if(i.id == 1){
       Log.d("TAG", i.toString())
      }
     }
      //second method: directly
      Log.d("TAG",markerData[0].toString())
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      相关资源
      最近更新 更多