Created
February 8, 2012 04:10
-
-
Save ejain/1765376 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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