GPS coordinate clustering for photo albums with DBSCAN and Vision

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
GPS coordinate clustering for photo albums with DBSCAN and Vision
Medium
~5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    745
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1162
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    563

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 UICollectionViewDiffableDataSource for 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

  1. Analysis — studying source data, EXIF structure, UI requirements.
  2. Design — selecting clustering models, geocoder, caching scheme.
  3. Implementation — writing modules for collection, clustering, geocoding, classification.
  4. Testing — validation on real photo libraries (up to 10,000 shots).
  5. 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.

Machine Learning in Mobile Apps: CoreML, TFLite, and On-Device Models

We distinguish two fundamentally different approaches: an app with on-device AI and an app that simply calls a cloud API. The former works without internet, does not send user data to third-party servers, and responds within 50 milliseconds. The latter depends on network latency and pricing plans. Choosing the architecture is a key step that directly affects cost, privacy, and user experience in machine learning in mobile apps. Our experience shows that in 70% of projects, on-device inference is cheaper in the long run due to eliminating server costs.

How to Choose Between CoreML and TFLite for On-Device Inference?

CoreML — Apple's native framework for running ML models on device. Supports Neural Engine (starting with A11 Bionic), GPU, and CPU as fallback. Models are converted to .mlmodel format via coremltools from PyTorch, ONNX, or TensorFlow. Conversion is not always trivial: custom layers require implementing MLCustomLayer, and INT8 quantization can sometimes noticeably reduce accuracy on specific data. We ensure the final model passes validation on real data before and after conversion.

TensorFlow Lite — cross-platform alternative for Android and Flutter. On Android it uses NNAPI (Neural Networks API) for hardware acceleration — since Android 10 NNAPI is more stable; before that it's better to explicitly use GPU delegate via GpuDelegate. A typical mistake: the model is trained on normalized data in range [0,1], but the app feeds [0,255] — inference runs but produces meaningless results without any error. We include an automatic input data validation module in the SDK.

For image classification, object detection, and segmentation tasks, ready-to-use optimized models are available. YOLOv8 in CoreML format runs detection on a 640×640 frame in 15–20 ms on iPhone 14 Neural Engine. MobileNetV3 on TFLite with GPU delegate runs around 8 ms on Pixel 7 for classification.

Parameter CoreML TFLite
Platforms iOS, macOS, watchOS Android, iOS, Linux, embedded
Hardware acceleration Neural Engine, GPU, CPU NNAPI, GPU (OpenCL/OpenGL), CPU
Quantization support FP16, INT8 (with coremltools) FP16, INT8, dynamic range
Custom operations Via MLCustomLayer (Swift) Via delegates (Java/Kotlin)
Model bundle size ~3–5 MB (MobileNetV2 quantized) ~2–4 MB

What If You Need Text Generation On-Device?

Running small language models on device has become a reality in the last few years. Apple Intelligence uses its own models via Private Cloud Compute, but for third-party developers other paths are available.

llama.cpp with Metal backend on iOS is a working approach for phi-3-mini (3.8B parameters, 4-bit quantization, ~2.3 GB). Inference: 15–25 tokens/second on iPhone 15 Pro. For integration in Swift, use the Swift Package llama.swift or a wrapper via C interface llama.h. The binary is not bundled with the app — the model is downloaded on first launch and stored in Application Support. Our certified developers configure incremental download to avoid blocking the first launch.

On Android, the analog is Google AI Edge (formerly MediaPipe LLM Inference API) supporting Gemma-2B. It works via GPU delegate, on Tensor G3 chip Pixel 8 Pro — about 20 tokens/second.

Limitations are real: models larger than 4B parameters are still slow on mobile devices. For complex reasoning tasks, on-device LLM falls behind GPT-4o in quality. A hybrid approach — on-device for short tasks and private data, cloud for complex queries — is often optimal. We will evaluate your case and propose a balance of performance and privacy — contact us.

How Does On-Device Inference Compare to Cloud in Terms of Cost and Performance?

On-device inference is typically 10x cheaper per request than cloud APIs for image recognition tasks, while also eliminating latency variability and privacy risks. The table below summarizes the trade-offs.

Criteria On-Device Inference Cloud API
Latency <50ms 200–500ms (including network)
Cost per 1M requests $0 (no server) $10–50 (AWS Rekognition, Google Vision)
Privacy Data stays on device Data sent to server
Offline Yes No
Scalability No server scaling issues Need to provision API capacity

For an app with 100k MAU running 10 image recognitions per user per month, on-device inference can save up to $5,000 monthly compared to cloud API. Get a free consultation on your ML architecture today.

Integrating OpenAI API and Other Cloud Models

For scenarios where cloud inference is acceptable, integrating OpenAI, Anthropic, or Google Gemini is an HTTP client + streaming SSE. In Swift, AsyncThrowingStream is convenient for streaming responses. In Kotlin, use Flow.

Critically: API keys must never be stored in the app bundle. Even an obfuscated key can be extracted from the IPA in 10 minutes using strings or frida. Correct architecture: mobile app → your own backend → OpenAI API. The backend controls rate limiting, logs requests, and protects the key.

What Is Included in the Work (Deliverables)

  • Trained and quantized model for the target device (documentation with metrics)
  • SDK for integration (Swift/Kotlin/Flutter) with call examples
  • Performance tests on 3–5 real devices
  • Instructions for OTA model updates
  • Support during App Store / Google Play moderation (compliance with Guidelines 4.2, 5.1)
  • 2 weeks of technical support after release

Typical Project Pipeline

  1. Task analysis — measure latency, privacy, size, supported devices.
  2. Model prototyping — in Python, evaluate accuracy on target data.
  3. Conversion and quantization — for CoreML/TFLite with validation.
  4. Integration into the app — model wrapped in a service layer (easy to swap CoreML ↔ TFLite ↔ cloud).
  5. Testing — on real devices, measure FPS, RAM, battery.
  6. Deployment — via TestFlight / Firebase App Distribution, monitor metrics.

Timelines: integration of a ready CoreML/TFLite model — 1–2 weeks, development of a custom model with mobile optimization — from 6 weeks, on-device LLM chat with personalization — 4–8 weeks.

Why We Take on Complex Cases?

10+ years of experience in mobile development, 50+ implemented AI/ML solutions, guarantee of compatibility with current iOS and Android versions. All projects undergo code review and load testing. The cost includes preparation of moderation documentation and training of your team.

Contact us — we will help you choose the architecture and implement ML in your app turnkey. Order an audit of your existing solution — we will assess the potential for server cost savings free of charge. In some projects, savings can reach significant amounts per month.