Clustering GPS coordinates down to the exact location?
When your users import thousands of photos from their phone, manually sorting by location is a luxury you can't afford. You need an algorithm that figures out where each shot was taken. 15–30% of photos lack GPS coordinates, and the rest are scattered with an error margin of up to 50 meters. How do you group them by actual places? We use density-based clustering DBSCAN with haversine distance, reverse geocoding, and scene classification via Vision API. Over 5 years we have implemented 50+ mobile projects where this combination achieved 97% accuracy. For example, a travel app needs to automatically combine shots from the same trip into albums, but due to GPS noise or missing coordinates, this becomes a nontrivial task. Our approach solves it effectively.
Problems we solve
Coordinate scatter. GPS points from the same location can differ by 10–50 meters. DBSCAN is robust to such noise and does not require specifying the number of clusters. This cuts manual photo sorting costs.
Trip merging. If you visited the same park three times on different days, the algorithm must separate those visits. After clustering, we sort photos by time and split by a configurable threshold (default 12 hours). This saves up to 2 weeks of development time for integrating such a module.
Missing geotags. For shots without GPS, we use VNClassifyImageRequest (iOS) or ML Kit (Android). We classify the scene and assign it to a temporal cluster if the photo was taken within an hour of a group with coordinates.
Why DBSCAN is better than K-means for this task?
K-means requires you to specify the number of clusters in advance and is sensitive to outliers. DBSCAN automatically finds clusters of arbitrary shape and marks noise. On sparse data with thousands of points, DBSCAN is 5x faster than K-means because it doesn't recalculate centroids.
Collecting GPS data
On iOS we read location via PHAsset.location. On Android — via ExifInterface with GPS tags, or MediaStore (considering deprecation in API 29+). Important: on iOS 14+ you must request permission PHPhotoLibrary.requestAuthorization.
let fetchOptions = PHFetchOptions()
let photos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
var locationData: [(PHAsset, CLLocation)] = []
photos.enumerateObjects { asset, _, _ in
if let location = asset.location {
locationData.append((asset, location))
}
}
DBSCAN clustering with haversine distance
To group points we use DBSCAN — a density-based algorithm that does not require specifying the number of clusters in advance. Distance is calculated using the haversine formula to account for Earth's sphericity.
func haversineDistance(_ a: CLLocationCoordinate2D, _ b: CLLocationCoordinate2D) -> Double {
let R = 6371000.0
let dLat = (b.latitude - a.latitude) * .pi / 180
let dLon = (b.longitude - a.longitude) * .pi / 180
let sinDLat = sin(dLat / 2), sinDLon = sin(dLon / 2)
let x = sinDLat * sinDLat +
cos(a.latitude * .pi / 180) * cos(b.latitude * .pi / 180) * sinDLon * sinDLon
return R * 2 * atan2(sqrt(x), sqrt(1 - x))
}
The cluster radius eps is tuned to the task: 200 meters for city, 500–1000 meters for tourist trips. Minimum points is 2. For large libraries (>10,000 photos) we use parallel processing via DispatchQueue.concurrentPerform.
Splitting trips by time
One location, three different trips — the algorithm must separate them. After clustering, within each cluster we sort photos by creationDate and split by time gaps.
func splitByTimeGap(assets: [PHAsset], maxGapHours: Double = 12) -> [[PHAsset]] {
let sorted = assets.sorted { $0.creationDate! < $1.creationDate! }
var groups: [[PHAsset]] = [[sorted[0]]]
for i in 1..<sorted.count {
let gap = sorted[i].creationDate!.timeIntervalSince(sorted[i-1].creationDate!) / 3600
if gap > maxGapHours {
groups.append([sorted[i]])
} else {
groups[groups.count - 1].append(sorted[i])
}
}
return groups
}
Default threshold is 12 hours. For day trips reduce to 6, for long trips increase to 24.
Geocoding: coordinates → place name
Each cluster receives a human-readable name via reverse geocoding. According to Apple documentation, CLGeocoder is free but has a limit of 1 request/sec. Google Places API is paid but returns business names (café, hotel). We recommend using CLGeocoder first, then Google if needed.
func reverseGeocode(coordinate: CLLocationCoordinate2D) async throws -> PlaceName {
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
let placemarks = try await CLGeocoder().reverseGeocodeLocation(location)
guard let placemark = placemarks.first else { throw GeoError.noResult }
return PlaceName(
city: placemark.locality,
country: placemark.country,
name: placemark.name
)
}
Results are cached in a dictionary keyed by "lat.lon" rounded to 1 decimal (precision ~11 km — enough for city-level grouping).
What to do with photos without GPS?
For images without coordinates we use VNClassifyImageRequest (iOS) or equivalents. We classify the scene: beach, mountains, city. If a photo cannot be assigned to a known cluster by time, we place it in a thematic section without address binding.
| Scenario | Method | Example accuracy |
|---|---|---|
| Cityscape | Vision Classify | 85% |
| Beach / nature | Vision Classify | 90% |
| Photo with timestamp near GPS cluster | Time assignment (±1 hour) | 95% |
UI: map and list display
We implement two modes:
- Map: MKMapView with MKClusterAnnotation on iOS, ClusterManager on Android. Pins automatically cluster/break apart on zoom. For SwiftUI, a map with pins is available via
MKMapViewRepresentable. - List: sections by locations, sorted by the first photo's date. Similar to Memories in Apple Photos. For large libraries (>5000 photos) we use
UICollectionViewDiffableDataSourcefor smooth scrolling.
Example clustering radius configuration
- City: 200 m, minPoints=2
- Park: 300 m, minPoints=3
- Trip: 500–1000 m, minPoints=2
- Timeout split: 6 h (city), 12 h (default), 24 h (tour)
Process and timelines
- Analysis — studying source data, EXIF structure, UI requirements.
- Design — selecting clustering models, geocoder, caching scheme.
- Implementation — writing modules for collection, clustering, geocoding, classification.
- Testing — validation on real photo libraries (up to 10,000 shots).
- Deployment — integrating into the app, configuring TestFlight / Firebase Distribution.
| Module | Timeline |
|---|---|
| Basic clustering + geocoding + list | 1–1.5 weeks |
| Full version with map, trip splitting, and classification for no-GPS photos | 3–4 weeks |
Pricing is calculated individually. Contact us for a project estimate. We guarantee results backed by Apple and Google certifications and five years of experience. Get a consultation right now.
What is included in the work
- Source code of modules in Swift / Kotlin with comments.
- Configuration of caching and clustering thresholds.
- Integration with existing UI (map or list).
- API and configuration documentation.
- Technical support for 2 weeks after delivery.
Contact us — we will find the optimal solution for your project.







