Skip to content

Instantly share code, notes, and snippets.

@jjhoncv
Created November 25, 2014 21:01
Show Gist options
  • Save jjhoncv/6f5c32b1395853fa34fe to your computer and use it in GitHub Desktop.
Save jjhoncv/6f5c32b1395853fa34fe to your computer and use it in GitHub Desktop.
<?php
define('OFFSET', 268435456);
define('RADIUS', 85445659.4471); /* $offset / pi() */
function lonToX($lon) {
return round(OFFSET + RADIUS * $lon * pi() / 180);
}
function latToY($lat) {
return round(OFFSET - RADIUS *
log((1 + sin($lat * pi() / 180)) /
(1 - sin($lat * pi() / 180))) / 2);
}
function pixelDistance($lat1, $lon1, $lat2, $lon2, $zoom) {
$x1 = lonToX($lon1);
$y1 = latToY($lat1);
$x2 = lonToX($lon2);
$y2 = latToY($lat2);
return sqrt(pow(($x1-$x2),2) + pow(($y1-$y2),2)) >> (21 - $zoom);
}
function cluster($markers, $distance, $zoom) {
$clustered = array();
/* Loop until all markers have been compared. */
while (count($markers)) {
$marker = array_pop($markers);
$cluster = array();
/* Compare against all markers which are left. */
foreach ($markers as $key => $target) {
$pixels = pixelDistance($marker['lat'], $marker['lon'],
$target['lat'], $target['lon'],
$zoom);
/* If two markers are closer than given distance remove */
/* target marker from array and add it to cluster. */
if ($distance > $pixels) {
printf("Distance between %s,%s and %s,%s is %d pixels.\n",
$marker['lat'], $marker['lon'],
$target['lat'], $target['lon'],
$pixels);
unset($markers[$key]);
$cluster[] = $target;
}
}
/* If a marker has been added to cluster, add also the one */
/* we were comparing to and remove the original from array. */
if (count($cluster) > 0) {
$cluster[] = $marker;
$clustered[] = $cluster;
} else {
$clustered[] = $marker;
}
}
return $clustered;
}
$markers = array();
$markers[] = array('id' => 'marker_1',
'lat' => 59.441193, 'lon' => 24.729494);
$markers[] = array('id' => 'marker_2',
'lat' => 59.432365, 'lon' => 24.742992);
$markers[] = array('id' => 'marker_3',
'lat' => 59.431602, 'lon' => 24.757563);
$markers[] = array('id' => 'marker_4',
'lat' => 59.437843, 'lon' => 24.765759);
$markers[] = array('id' => 'marker_5',
'lat' => 59.439644, 'lon' => 24.779041);
$markers[] = array('id' => 'marker_6',
'lat' => 59.434776, 'lon' => 24.756681);
$clustered = cluster($markers, 10, 11);
echo json_encode($clustered)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment