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 all 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,68 @@
/*
* 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.ClusterItem;
import com.google.maps.android.geometry.Bounds;
import com.google.maps.android.quadtree.PointQuadTree;

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

/**
* A variant of {@link CentroidNonHierarchicalDistanceBasedAlgorithm} that uses
* continuous zoom scaling and Euclidean distance for clustering.
*
* <p>This class overrides {@link #getClusteringItems(PointQuadTree, float)} to compute
* clusters with a zoom-dependent radius, while keeping the centroid-based cluster positions.</p>
*
* @param <T> the type of cluster item
*/
public class ContinuousZoomEuclideanCentroidAlgorithm<T extends ClusterItem>
extends CentroidNonHierarchicalDistanceBasedAlgorithm<T> {

@Override
protected Collection<QuadItem<T>> getClusteringItems(PointQuadTree<QuadItem<T>> quadTree, float zoom) {
// Continuous zoom — no casting to int
final double zoomSpecificSpan = getMaxDistanceBetweenClusteredItems() / Math.pow(2, zoom) / 256;

final Set<QuadItem<T>> visitedCandidates = new HashSet<>();
final Collection<QuadItem<T>> result = new ArrayList<>();
synchronized (mQuadTree) {
for (QuadItem<T> candidate : mItems) {
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);
}
}

visitedCandidates.addAll(clusterItems);
result.add(candidate);
}
}
return result;
}

}
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 @@ -53,12 +54,12 @@ public class NonHierarchicalDistanceBasedAlgorithm<T extends ClusterItem> extend
/**
* Any modifications should be synchronized on mQuadTree.
*/
private final Collection<QuadItem<T>> mItems = new LinkedHashSet<>();
protected final Collection<QuadItem<T>> mItems = new LinkedHashSet<>();

/**
* 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 @@ -246,11 +247,25 @@ public int getMaxDistanceBetweenClusteredItems() {
return mMaxDistance;
}

private double distanceSquared(Point a, Point b) {
/**
* 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}
*/
protected double distanceSquared(Point a, Point b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}

private Bounds createBoundsFromSpan(Point p, double span) {
/**
* 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
*/
protected Bounds createBoundsFromSpan(Point p, double span) {
// TODO: Use a span that takes into account the visual size of the marker, not just its
// LatLng.
double halfSpan = span / 2;
Expand All @@ -260,7 +275,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,117 @@
/*
* 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 ContinuousZoomEuclideanCentroidAlgorithmTest {

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() {
ContinuousZoomEuclideanCentroidAlgorithm<TestClusterItem> algo =
new ContinuousZoomEuclideanCentroidAlgorithm<>();

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);

// 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);
}

@Test
public void testClusterPositionsAreCentroids() {
ContinuousZoomEuclideanCentroidAlgorithm<TestClusterItem> algo =
new ContinuousZoomEuclideanCentroidAlgorithm<>();

Collection<TestClusterItem> items = Arrays.asList(
new TestClusterItem(0.0, 0.0),
new TestClusterItem(0.0, 2.0),
new TestClusterItem(2.0, 0.0)
);

algo.addItems(items);

Set<? extends Cluster<TestClusterItem>> clusters = algo.getClusters(1.0f);

// Expect all items clustered into one
assertEquals(1, clusters.size());

Cluster<TestClusterItem> cluster = clusters.iterator().next();

// The centroid should be approximately (0.6667, 0.6667)
LatLng centroid = cluster.getPosition();
assertEquals(0.6667, centroid.latitude, 0.0001);
assertEquals(0.6667, centroid.longitude, 0.0001);
}
}