Skip to content

feat: added ContinuousZoomEuclideanCentroidAlgorithm #1559

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.maps.android.clustering.algo;

import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterItem;
import com.google.maps.android.geometry.Bounds;
import com.google.maps.android.geometry.Point;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
* A variant of {@link NonHierarchicalDistanceBasedAlgorithm} that supports:
* <ul>
* <li><strong>Continuous zoom-based clustering</strong> — the clustering radius
* changes smoothly with the zoom level, rather than stepping at integer zoom levels.</li>
* <li><strong>Euclidean distance metric</strong> — items are clustered based on their
* true Euclidean distance in projected map coordinates, instead of relying solely on
* rectangular bounds overlap.</li>
* </ul>
*
* <p>This algorithm overrides {@link #getClusters(float)} to calculate clusters using a
* zoom-dependent span and a circular radius check, improving visual stability during zoom
* animations and producing clusters that are spatially more uniform.</p>
*
* @param <T> the type of cluster item
*/
public class ContinuousZoomEuclideanAlgorithm<T extends ClusterItem>
extends NonHierarchicalDistanceBasedAlgorithm<T> {

/**
* Returns clusters for the given zoom level using continuous zoom scaling and
* a Euclidean distance threshold.
*
* <p>The algorithm works as follows:</p>
* <ol>
* <li>Computes a {@code zoomSpecificSpan} in projected coordinates based on the
* current zoom level and the configured maximum clustering distance.</li>
* <li>Iterates over unvisited items in the quadtree.</li>
* <li>For each candidate item, searches nearby items within a bounding box
* derived from {@code zoomSpecificSpan}.</li>
* <li>Filters those items by actual Euclidean distance to ensure they fall
* within a circular clustering radius.</li>
* <li>Creates a {@link StaticCluster} if more than one item is within range,
* otherwise treats the item as its own singleton cluster.</li>
* </ol>
*
* @param zoom the current map zoom level (fractional values supported)
* @return a set of clusters computed with continuous zoom and Euclidean distance
*/
@Override
public Set<? extends Cluster<T>> getClusters(float zoom) {
final double zoomSpecificSpan = getMaxDistanceBetweenClusteredItems()
/ Math.pow(2, zoom) / 256;

final Set<QuadItem<T>> visitedCandidates = new HashSet<>();
final Set<Cluster<T>> results = new HashSet<>();
final Map<QuadItem<T>, Double> distanceToCluster = new HashMap<>();
final Map<QuadItem<T>, StaticCluster<T>> itemToCluster = new HashMap<>();

synchronized (mQuadTree) {
for (QuadItem<T> candidate : getClusteringItems(mQuadTree, zoom)) {
if (visitedCandidates.contains(candidate)) {
continue;
}

Bounds searchBounds = createBoundsFromSpan(candidate.getPoint(), zoomSpecificSpan);
Collection<QuadItem<T>> clusterItems = new ArrayList<>();
for (QuadItem<T> clusterItem : mQuadTree.search(searchBounds)) {
double distance = distanceSquared(clusterItem.getPoint(), candidate.getPoint());
double radiusSquared = Math.pow(zoomSpecificSpan / 2, 2);
if (distance < radiusSquared) {
clusterItems.add(clusterItem);
}
}

if (clusterItems.size() == 1) {
results.add(candidate);
visitedCandidates.add(candidate);
distanceToCluster.put(candidate, 0d);
continue;
}

StaticCluster<T> cluster = new StaticCluster<>(candidate.getPosition());
results.add(cluster);

for (QuadItem<T> clusterItem : clusterItems) {
Double existingDistance = distanceToCluster.get(clusterItem);
double distance = distanceSquared(clusterItem.getPoint(), candidate.getPoint());
if (existingDistance != null && existingDistance < distance) {
continue;
}
if (existingDistance != null) {
itemToCluster.get(clusterItem).remove(clusterItem.mClusterItem);
}
distanceToCluster.put(clusterItem, distance);
cluster.add(clusterItem.mClusterItem);
itemToCluster.put(clusterItem, cluster);
}

visitedCandidates.addAll(clusterItems);
}
}
return results;
}

/**
* Calculates the squared Euclidean distance between two points.
*
* @param a the first point
* @param b the second point
* @return the squared Euclidean distance between {@code a} and {@code b}
*/
private double distanceSquared(Point a, Point b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}

/**
* Creates a square bounding box centered at a point with the specified span.
*
* @param p the center point
* @param span the total width/height of the bounding box
* @return the {@link Bounds} object representing the search area
*/
private Bounds createBoundsFromSpan(Point p, double span) {
double halfSpan = span / 2;
return new Bounds(
p.x - halfSpan, p.x + halfSpan,
p.y - halfSpan, p.y + halfSpan
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.google.maps.android.projection.SphericalMercatorProjection;
import com.google.maps.android.quadtree.PointQuadTree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -58,7 +59,7 @@ public class NonHierarchicalDistanceBasedAlgorithm<T extends ClusterItem> extend
/**
* Any modifications should be synchronized on mQuadTree.
*/
private final PointQuadTree<QuadItem<T>> mQuadTree = new PointQuadTree<>(0, 1, 0, 1);
protected final PointQuadTree<QuadItem<T>> mQuadTree = new PointQuadTree<>(0, 1, 0, 1);

private static final SphericalMercatorProjection PROJECTION = new SphericalMercatorProjection(1);

Expand Down Expand Up @@ -260,7 +261,7 @@ private Bounds createBoundsFromSpan(Point p, double span) {
}

protected static class QuadItem<T extends ClusterItem> implements PointQuadTree.Item, Cluster<T> {
private final T mClusterItem;
protected final T mClusterItem;
private final Point mPoint;
private final LatLng mPosition;
private Set<T> singletonSet;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.maps.android.clustering.algo;

import androidx.annotation.NonNull;

import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterItem;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ContinuousZoomEuclideanAlgorithmTest {

static class TestClusterItem implements ClusterItem {
private final LatLng position;

TestClusterItem(double lat, double lng) {
this.position = new LatLng(lat, lng);
}

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

@Override
public String getTitle() {
return null;
}

@Override
public String getSnippet() {
return null;
}

@Override
public Float getZIndex() {
return 0f;
}
}

@Test
public void testContinuousZoomMergesClosePairAtLowZoomAndSeparatesAtHighZoom() {
ContinuousZoomEuclideanAlgorithm<TestClusterItem> algo =
new ContinuousZoomEuclideanAlgorithm<>();

Collection<TestClusterItem> items = Arrays.asList(
new TestClusterItem(10.0, 10.0),
new TestClusterItem(10.0001, 10.0001), // very close to the first
new TestClusterItem(20.0, 20.0) // far away
);

algo.addItems(items);

// At a high zoom, the close pair should be separate (small radius)
Set<? extends Cluster<TestClusterItem>> highZoom = algo.getClusters(20.0f);
assertEquals(3, highZoom.size());

// At a lower zoom, the close pair should merge (larger radius)
Set<? extends Cluster<TestClusterItem>> lowZoom = algo.getClusters(5.0f);
assertTrue(lowZoom.size() < 3);

// And specifically, we expect one cluster of size 2 and one singleton
boolean hasClusterOfTwo = lowZoom.stream().anyMatch(c -> c.getItems().size() == 2);
boolean hasClusterOfOne = lowZoom.stream().anyMatch(c -> c.getItems().size() == 1);
assertTrue(hasClusterOfTwo);
assertTrue(hasClusterOfOne);
}
}