Map Clustering in Android

by Aamir Bhatt

Maps are the visual  representation of an area. Android provides Api support through Google map Android v2 API .

Setting up map :

Set up following for Google map in your project:

  • Setup google play Services SDK
  • Obtain an API key
  • Specify api key in manifest
  • Specify following permission
    • INTERNET
    • ACCESS_NETWORK_STATE

In the activity layout add this fragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"

    android:name="com.google.android.gms.maps.SupportMapFragment"

    android:id="@+id/map"

    android:layout_width="match_parent"

    android:layout_height=“match_parent"/>
 
Map is visualised on the screen without any markers or cluster in the activity on creating method.
get reference to map fragment

map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

 get cluster manager instance

mClusterManager = new ClusterManager<Place>(DashboardActivity.this, Map);

 add places to the cluster manager

 mClusterManager.addItem(new Place(Double.parseDouble(lat)), Double.parseDouble(lng)))

We can add n number of places to the mClusterManager by iterating through the places and calling

//after adding all the items 

mClusterManager.cluster();
//this will cluster all the place

This is a simple Google map cluster. Let’s override the default cluster feature.

Public class StepClusterRendered extends DefaultClusterRenderer {
@Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
    return cluster.getSize() > 1;
}
// by default if  4 markers are closer to each other then only cluster manager  makes cluster of those marker,override the
shouldRenderAsCluster to choose your cluster size
// if we change the layout image of markers
@Override
protected void onBeforeClusterItemRendered(Place item, MarkerOptions markerOptions) {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap)
}
//if we change the layout image of cluster
protected void onClusterRendered(Cluster cluster, Marker marker) {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(br));
}
}

This is how we can override the default behavior of cluster.

Leave a Reply

Your email address will not be published. Required fields are marked *

Mobile Research Apps

We have deep expertise in design and development of mobile research apps that work on both iOS and Android securely.

Contact us now

Popular Posts