Android Maps Point Clustering

前端 未结 7 1652
春和景丽
春和景丽 2020-11-29 17:18

Is there any code for Point Clustering in android? How can i load thousand pinpoint without having performance issues?

相关标签:
7条回答
  • 2020-11-29 18:08

    Google's Android Map Utils has a solution for this: Google Maps Android Marker Clustering Utility.

    Add dependency

    implementation 'com.google.maps.android:android-maps-utils:0.5'
    

    Make your own ClusterItem

    class MyItem(
            private val position: LatLng,
            val title: String,
            private val snippet: String
    ) : ClusterItem {
        override fun getPosition() = position
        override fun getTitle() = title
        override fun getSnippet() = snippet
    }
    

    Setting up the cluster manager and adding items

    override fun onMapReady(googleMap: GoogleMap) {
        val clusterManager = ClusterManager<MyItem>(this, googleMap)
        googleMap.setOnCameraIdleListener(clusterManager)
    
        clusterManager.addItem(MyItem(LatLng(51.51, -0.12), "title", "snippet"))
    }
    

    That's it! Items are now shown as follows:

    Customizing the icon

    In order to customize the icon, add val icon: BitmapDescriptor to your ClusterItem and change the renderer of the cluster manager:

        clusterManager.renderer = object : DefaultClusterRenderer<MyItem>(this, googleMap, clusterManager) {
            override fun onBeforeClusterItemRendered(item: MyItem, markerOptions: MarkerOptions) {
                markerOptions.icon(item.icon)
            }
        }
    

    Making items clickable

    As a rule of thumb, any interaction with markers should go through the cluster manager instead. The same applies to making items clickable.

        googleMap.setOnMarkerClickListener(clusterManager)
        clusterManager.setOnClusterItemClickListener {
            Toast.makeText(this, "Clicked on item ${it.title}", Toast.LENGTH_SHORT).show()
            true
        }
    

    Similarly, you can call googleMap.setOnInfoWindowClickListener(clusterManager) and clusterManager.setOnClusterItemInfoWindowClickListener to handle clicks on the info window.

    0 讨论(0)
提交回复
热议问题