How to implement Marker Clustering for Google Maps

2020-06-06 05:40发布

问题:

I have implemented Google Maps successfully in my App. I have to implement Marker Clustering for Xamarin Android.

The link here gives a good explanation regarding how to implement but i am not able to understand how to refer the package.

I got few source files but it is not helping as i am not aware how to refer the jar files. The documents i got is related to Java but not C#. Here are the few links:

https://github.com/googlemaps/android-maps-utils https://forums.xamarin.com/discussion/13569/google-maps-android-api-utility-library-support/p2?

回答1:

You want to use the Xamarin.Android Binding project that includes the android-maps-utils.aar file.

Note: I have forked an older Github repo that included a binding project and example and updated it to the latest version of android-maps-utils.aar (v0.4.3 as of this post).

Just clone that repo and copy the entire GoogleMapsUtility project into your Xamarin.Android solution and add that to your solution (via Add Existing Project).

Then you can create a Google Map like you would normally, i.e.:

GoogleMapOptions mapOptions = new GoogleMapOptions()
    .InvokeMapType(GoogleMap.MapTypeNormal)
    .InvokeZoomControlsEnabled(true)
    .InvokeMapToolbarEnabled(true)
    .InvokeZoomGesturesEnabled(true)
    .InvokeRotateGesturesEnabled(true)
    .InvokeCompassEnabled(true);

Then you can add your Map markers to the ClusterManager and let it manage the clustering:

_clusterManager = new ClusterManager(this, _map);
_clusterManager.SetOnClusterClickListener(this);
_clusterManager.SetOnClusterItemClickListener(this);
_map.SetOnCameraChangeListener(_clusterManager);
_map.SetOnMarkerClickListener(_clusterManager);

I modified the original example to create 20 markers in a log. spiral pattern to test the cluster at various zoom levels:

private void AddClusterItems()
{
    double lat = 47.59978;
    double lng = -122.3346;

    var items = new List<ClusterItem>();

    // Create a log. spiral of markers to test clustering
    for (int i = 0; i < 20; ++i)
    {
        var t = i * Math.PI * 0.33f;
        var r = 0.005 * Math.Exp(0.1 * t);
        var x = r * Math.Cos(t);
        var y = r * Math.Sin(t);
        var item = new ClusterItem(lat + x, lng + y);
        items.Add(item);
    }
    _clusterManager.AddItems(items);
}