Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created August 5, 2011 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simenbrekken/1127116 to your computer and use it in GitHub Desktop.
Save simenbrekken/1127116 to your computer and use it in GitHub Desktop.
Clustering algorithm
var MAX_ZOOM = 21;
var OFFSET = 268435456;
var RADIUS = 85445659.4471;
var latToY = function(value) {
return Math.round(OFFSET - RADIUS * Math.log((1 + Math.sin(value * Math.PI / 180)) / (1 - Math.sin(value * Math.PI / 180))) / 2);
};
var lngToX = function(value) {
return Math.round(OFFSET + RADIUS * value * Math.PI / 180);
};
var pixelDistance = function(p1, p2, zoom) {
var x1 = lngToX(p1.lng);
var y1 = latToY(p1.lat);
var x2 = lngToX(p2.lng);
var y2 = latToY(p2.lat);
return Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)) >> (MAX_ZOOM - zoom);
};
exports.walks = function(walks, minDistance, zoom) {
var clusters = [];
while (walks.length > 0) {
var walk = walks.pop();
var cluster = [];
walks.forEach(function(adjacent, i) {
var distance = pixelDistance(walk.startPoint, adjacent.startPoint, zoom);
if (minDistance > distance) {
walks.splice(i, 1);
cluster.push(adjacent);
}
});
if (cluster.length > 0) {
cluster.push(walk);
clusters.push(cluster);
} else {
clusters.push(walk);
}
}
return clusters;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment