我发现谷歌的开发网站上大多只有Java代码示例,Kotlin中也很少,这很烦人,所以我不得不在这里问这个问题。
我正在尝试设置一个集群管理器,但我没有任何线索应该如何完成,也没有看到 Kotlin 示例。我确实做到了这一点:
override fun onMapReady(googleMap: GoogleMap) {
// return early if the map was not initialised properly
mMap = googleMap ?: return
with(mMap.uiSettings) {
isZoomControlsEnabled = true
isMyLocationButtonEnabled = true
isCompassEnabled = true
isRotateGesturesEnabled = true
isZoomGesturesEnabled = true
}
val clusterManager = ClusterManager<ScootMarker>(this, mMap)
mMap.setOnCameraIdleListener(clusterManager)
mMap.setOnMarkerClickListener(clusterManager)
mMap.setOnInfoWindowClickListener(clusterManager)
mMap.setInfoWindowAdapter(CustomInfoWindowAdapter(this))
mMap.mapType = GoogleMap.MAP_TYPE_HYBRID
setUpMap()
getData()
}
但是,我不知道应该如何向该群集管理器添加标记,也不知道如何将其绑定到我的CustomInfoWindowAdapter。
我已经完成了自己的自定义项目,它返回代码段、位置和标题。
请尝试下面的代码,以获取有关如何在 Kotlin 中添加标记集群器的指导和演示。
class MyItem : ClusterItem {
private val mPosition: LatLng
private val mTitle: String
private val mSnippet: String
constructor(lat: Double, lng: Double) {
mPosition = LatLng(lat, lng)
mTitle = ""
mSnippet = ""
}
constructor(lat: Double, lng: Double, title: String, snippet: String) {
mPosition = LatLng(lat, lng)
mTitle = title
mSnippet = snippet
}
override fun getPosition(): LatLng {
return mPosition
}
override fun getTitle(): String {
return mTitle
}
override fun getSnippet(): String {
return mSnippet
}
}
class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener {
private lateinit var mMap: GoogleMap
private lateinit var mClusterManager: ClusterManager<MyItem>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
setUpClusterer()
mMap.setOnInfoWindowClickListener(this);
}
private fun setUpClusterer() {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(51.503186, -0.126446), 10f))
mClusterManager = ClusterManager(this, mMap)
mMap.setOnCameraIdleListener(mClusterManager)
mMap.setOnMarkerClickListener(mClusterManager)
addItems()
}
private fun addItems() {
var lat = 51.5145160
var lng = -0.1270060
for (i in 0..9) {
val offset = i / 60.0
lat = lat + offset
lng = lng + offset
val title = "This is the title"
val snippet = "and this is the snippet."
val offsetItem = MyItem(lat, lng, title, snippet)
mClusterManager.addItem(offsetItem)
}
}
override fun onInfoWindowClick(marker: Marker) {
Toast.makeText(
this, "Info window clicked",
Toast.LENGTH_SHORT
).show()
}
}
请注意,这是基于 Google 指南 [1] [2] 中的 Java 代码实现,它对我来说没有问题,所以我希望这对您有所帮助!
[1] https://developers.google.com/maps/documentation/android-sdk/utility/marker-clustering
[2] https://developers.google.com/maps/documentation/android-sdk/infowindows