Skip to content

Instantly share code, notes, and snippets.

@tomires
Last active September 8, 2022 08:33
Show Gist options
  • Save tomires/bba62ef7949018ee4d75cebefb0f69c3 to your computer and use it in GitHub Desktop.
Save tomires/bba62ef7949018ee4d75cebefb0f69c3 to your computer and use it in GitHub Desktop.
Clustering in Mapbox Unity
private static float MIN_PIN_DISTANCE = 8;
/* Prefab should include a TMP_Text component in its hierarchy
to be used for exposing number of clustered items to user */
[SerializeField] private GameObject clusterPinPrefab;
private Dictionary<GameObject, (int id, Vector2d coords)> _spawnedPins
= new Dictionary<GameObject, Vector2d>();
private Dictionary<GameObject, Vector2d> _spawnedClusterPins
= new Dictionary<GameObject, Vector2d>();
/* Call this function when user finishes the pinch-to-zoom gesture */
private void SpawnClusters()
{
foreach (var cluster in _spawnedClusterPins)
Destroy(cluster.Key);
_spawnedClusterPins.Clear();
foreach (var pin in _spawnedPins)
pin.Key.SetActive(true);
var pins = _spawnedPins.Keys.ToList();
for (int i = 0; i < pins.Count; i++)
{
var markerList = new List<GameObject>();
for (int j = i + 1; j < pins.Count; j++)
{
if (pins[j].activeInHierarchy == false) continue;
var distance = Vector3.Distance(
pins[i].transform.position,
pins[j].transform.position);
if (distance < MIN_PIN_DISTANCE)
{
markerList.Add(pins[i]);
markerList.Add(pins[j]);
pins[i].SetActive(false);
pins[j].SetActive(false);
j = i + 1;
}
}
if (markerList.Count > 0)
{
var cluster = Instantiate(clusterPinPrefab);
cluster.transform.position = pins[i].transform.position;
cluster.GetComponentInChildren<TMPro.TMP_Text>().text = (markerList.Count / 2f + 1).ToString();
_spawnedClusterPins.Add(cluster, _spawnedPins[pins[i]].coords);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment