Skip to content

Instantly share code, notes, and snippets.

@ejain
Created February 8, 2012 04:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejain/1765376 to your computer and use it in GitHub Desktop.
Save ejain/1765376 to your computer and use it in GitHub Desktop.
class GeoClusterer {
private final double maxDistance;
private final List<GeoCluster> clusters = Lists.newArrayList();
public GeoClusterer(double maxDistance, DistanceUnit unit) {
this.maxDistance = unit.convert(maxDistance, unit, DistanceUnit.KILOMETERS);
}
public GeoCluster add(GeoPoint point) {
GeoCluster cluster = null;
double distance = Double.MAX_VALUE;
for (GeoCluster c : clusters) {
double d = distance(c.center(), point);
if (d < distance && d <= maxDistance) {
d = distance;
cluster = c;
}
}
if (cluster == null) {
cluster = new GeoCluster();
clusters.add(cluster);
}
cluster.add(point);
return cluster;
}
private double distance(GeoPoint left, GeoPoint right) {
return GeoDistance.ARC.calculate(left.getLat(), left.getLon(),
right.getLat(), right.getLon(), DistanceUnit.KILOMETERS);
}
public List<GeoCluster> getClusters() {
return clusters;
}
}
class GeoCluster {
private int size;
private GeoPoint center;
public void add(GeoPoint point) {
++size;
if (center == null) {
center = point;
}
else {
double lat = (center.getLat() * (size - 1) + point.getLat()) / size;
double lon = (center.getLon() * (size - 1) + point.getLon()) / size;
center = new GeoPoint(lat, lon);
}
}
public int size() {
return size;
}
public GeoPoint center() {
return center;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment