Evan
Evan

Reputation: 287

Add Title to Marker in Google Map Cluster

I'm creating an app with hundreds of markers so I decided implementing clustering was a good idea. However, I've run into the problem of adding a title to the markers in the cluster. I need this data to later retrieve items from JSON when I create the marker's info window. So to sum up my question is, how would I add a String as a title to each Marker in a cluster.

My current code:

public class MyItem implements ClusterItem {
    private final LatLng mPosition;

    public MyItem(double lat, double lng) {
        mPosition = new LatLng(lat, lng);
    }

    @Override
    public LatLng getPosition() {
        return mPosition;
    }
}

for (int i = 0; i < activity.m_jArry.length(); i++)
    {
        JSONObject j;
        try {
            j = activity.m_jArry.getJSONObject(i);
            mClusterManager.addItem(new MyItem(j.getDouble("lat"), j.getDouble("lon")));
            //mMap.addMarker(new MarkerOptions().title(j.getString("Unique")).snippet(i + "").position(new LatLng(j.getDouble("lat"), j.getDouble("lon"))));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Thanks for any help :)

Upvotes: 1

Views: 2512

Answers (1)

Ismaili Alaoui smail
Ismaili Alaoui smail

Reputation: 136

there is a global solution for you that help to add title, snippet and icon so you can get what you want.

Modify your ClusterItem Object and add 3 variables :

public class MyItem implements ClusterItem {

private final LatLng mPosition;
BitmapDescriptor icon;
String title;
String snippet;

public MyItem(BitmapDescriptor ic,Double lat , Double lng,String tit ,String sni)
{
    mPosition = new LatLng(lat,lng);
    icon = ic;
    title = tit;
    snippet = sni;

}

And after you create your costume render :

public class OwnRendring extends DefaultClusterRenderer<MyItem> {

    public OwnRendring(Context context, GoogleMap map,
                           ClusterManager<MyItem> clusterManager) {
        super(context, map, clusterManager);
    }


    protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {

        markerOptions.icon(item.getIcon());
        markerOptions.snippet(item.getSnippet());
        markerOptions.title(item.getTitle());
        super.onBeforeClusterItemRendered(item, markerOptions);
    }
}

After that just put this line in your SetUpCluster() function before addItems():

 mClusterManager.setRenderer(new OwnRendring(getApplicationContext(),mMap,mClusterManager));

Upvotes: 5

Related Questions