Clusterer


Source link: https://github.com/mrmans0n/clusterer

Clusterer

Clustering library for points of interest in Android v2 Maps.

Getting Started

You can add the project with maven or gradle via adding the appropiate dependence.

compile 'io.nlopez.clusterer:library:1.0.6'

Preparing your app

You should have a working Google Maps v2 (the one from Google Play Services 13+) in your application, with the proper keys and all the stuff needed. Then you should follow these steps.

In your Model

In the model you are using for referencing a point of interest, you should implement the Clusterable interface. That interface only needs a method that returns a LatLng position with the appropiate coordinates, called getPosition().

An example:

public class MyPoi implements Clusterable {
  private String name;  private LatLng position;
public MyPoi(String name, LatLng position) {

this.name = name;
this.position = position;  
}

public String getName() {
 return name; 
}

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

Where you have a reference to the GoogleMap object

In the class you are using the GoogleMap object, you must instance the Clusterer object.

 GoogleMap map;  Clusterer<MyPoi> clusterer;
// [...]
private void initClusterer() {

clustered = new Clusterer<MyPoi>(this, map);
  
}
 

The Clusterer will control your zoom and will reload the cluster markers when the zoom changes without your interaction.

NOTE You shouldn't control the GoogleMap.OnCameraChangeListener on your own anymore, you should let Clusterer handle it. If you want to add some functionality to it or control on your own, you should set that callback in Clusterer instead.

Example:

 clusterer.setOnCameraChangeListener(

new GoogleMap.OnCameraChangeListener() {

 @Override

 public void onCameraChange(CameraPosition cameraPosition) {

  // Do your thing in here

 
}
);

}

  );

Customization

You can customize the marker's appearance, even if it's a cluster marker. You have two listeners that will be invoked when the markers are being generated by the Clusterer and will be able to provide the markers with the MarkerOptions data we want.

Here you have an example that displays the value of an attribute called description from our PointOfInterest model as the subtitle, and an attribute name as the title. If the marker is a cluster, it will display a drawable with the number of points contained in the cluster painted on top of it.

  clusterer.setOnPaintingMarkerListener(new OnPaintingClusterableMarkerListener() {

  @Override
 public void onMarkerCreated(Marker marker, MyPoi clusterable) {

  // If you want to perform some animation or whatever, you could do it here
 
}

  @Override
 public MarkerOptions onCreateMarkerOptions(MyPoi poi) {

  return new MarkerOptions().position(clusterable.getPosition()).title(poi.getName()).snippet(poi.getDescription());

 
}

}
);

 clusterer.setOnPaintingClusterListener(new OnPaintingClusterListener() {

  @Override
 public void onMarkerCreated(Marker marker, Cluster cluster) {

  // If you want to perform some animation or whatever, you could do it here
 
}

  @Override
 public MarkerOptions onCreateClusterMarkerOptions(Cluster cluster) {

  return new MarkerOptions()

 .title("Clustering " + cluster.getWeight() + " items")

 .position(cluster.getCenter())

 .icon(BitmapDescriptorFactory.fromBitmap(

getClusteredLabel(cluster.getWeight(),

MainActivity.this)));

 
}

}
);

}

// A little method that creates a composition with an image from the drawables and the number of pois included in a particular cluster
  private Bitmap getClusteredLabel(Integer count, Context ctx) {

Resources r = ctx.getResources();

Bitmap res = BitmapFactory.decodeResource(r, R.drawable.circle_red);

res = res.copy(Bitmap.Config.ARGB_8888, true);

Canvas c = new Canvas(res);

 Paint textPaint = new Paint();

textPaint.setAntiAlias(true);

textPaint.setTextAlign(Paint.Align.CENTER);

textPaint.setTypeface(Typeface.DEFAULT_BOLD);

textPaint.setColor(Color.WHITE);

float density = getResources().getDisplayMetrics().density;

textPaint.setTextSize(16 * density);

 c.drawText(String.valueOf(count.toString()), res.getWidth() / 2, res.getHeight() / 2 + textPaint.getTextSize() / 3, textPaint);

 return res;
  
}

As you can see, the listeners for the interfaces OnPaintingClusterableMarkerListener and OnPaintingClusterListener let you do anything you want to the markers, whether if they are a cluster or a point of interest in their own.

You can take a look to the provided sample application.

License

The MIT License (MIT)

Copyright (c) 2013-2015 Nacho Lopez

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Resources

Searchable Spinner is a dialog spinner with the search feature which allows to search the items loaded in the spinner.

Collection of source codes, utilities, templates and snippets for Android development.

AndroidResizer is a simple Java desktop app for automatically re-sizing android assets.

AR will downscale your assets and copy them into an android-style folder structure.

Android & Pure Java library to shape a voice with an instrument.

NaturalLenguageProcessor is an Android library that wraps text-processing.com API and gives you the possibility to stem, to tag and to analyze sentimentally the text you want.

Layout that contains a ViewPager and can slide vertically between 2 states (expanded and collapsed).

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes