Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Core/Map/Clusterer.swift4// Description: regroupement des points de carte selon le zoom — pur, testable, hors du fil principal.5// Un point du service est une POSITION (un commerce, ou le centre d'une ville), pas un véhicule.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import CoreLocation12import Foundation1314/// Élément affiché sur la carte.15struct MapItem: Sendable, Hashable, Identifiable {16 enum Kind: Sendable, Hashable {17 /// un seul véhicule à cette position : étiquette de prix18 case vehicle(uid: String, price: Double?)19 /// plusieurs véhicules à la même position (un commerce ou le centre d'une ville)20 case lot(count: Int, minPrice: Double?, city: String?, dealerID: String?)21 /// plusieurs positions regroupées par le zoom22 case cluster(count: Int, minPrice: Double?)23 }24 var id: String25 var lat: Double26 var lng: Double27 var kind: Kind2829 var coordinate: CLLocationCoordinate2D { .init(latitude: lat, longitude: lng) }30 var count: Int {31 switch kind {32 case .vehicle: 133 case .lot(let c, _, _, _), .cluster(let c, _): c34 }35 }36}3738/// Zone visible de la carte (degrés).39struct MapBounds: Sendable, Hashable, Codable {40 var west: Double41 var south: Double42 var east: Double43 var north: Double4445 /// Paramètre `bbox` de l'API : ouest,sud,est,nord.46 var bbox: String { String(format: "%.5f,%.5f,%.5f,%.5f", west, south, east, north) }4748 func contains(lat: Double, lng: Double) -> Bool { lat >= south && lat <= north && lng >= west && lng <= east }4950 func padded(_ f: Double) -> MapBounds {51 let dx = (east - west) * f, dy = (north - south) * f52 return MapBounds(west: west - dx, south: south - dy, east: east + dx, north: north + dy)53 }5455 /// Le Québec habité, pour la vue d'ensemble.56 static let quebec = MapBounds(west: -79.6, south: 44.9, east: -64.0, north: 50.3)57}5859enum Clusterer {60 static func item(for p: MapPoint) -> MapItem {61 if p.n <= 1, let uid = p.uid {62 return MapItem(id: uid, lat: p.lat, lng: p.lng, kind: .vehicle(uid: uid, price: p.priceMin))63 }64 return MapItem(id: String(format: "l%.4f,%.4f-%d", p.lat, p.lng, p.n), lat: p.lat, lng: p.lng,65 kind: .lot(count: p.n, minPrice: p.priceMin, city: p.city, dealerID: p.dealerID))66 }6768 /// Regroupe les positions visibles sur une grille dont la maille suit la zone ; sous `singleThreshold`69 /// positions visibles, chacune garde son marqueur. Aucun véhicule n'est perdu : la somme des effectifs70 /// rendus égale celle des positions visibles (tant que `maxItems` n'est pas atteint).71 static func cluster(_ points: [MapPoint], in bounds: MapBounds, columns: Int = 6, aspect: Double = 1.6,72 singleThreshold: Int = 45, maxItems: Int = 140, pinned: String? = nil) -> [MapItem] {73 let area = bounds.padded(0.12)74 let w = max(area.east - area.west, 1e-9)75 let h = max(area.north - area.south, 1e-9)76 var visible = points.filter { area.contains(lat: $0.lat, lng: $0.lng) }77 var out: [MapItem] = []78 // le véhicule sélectionné reste toujours seul, jamais absorbé par un regroupement79 if let pinned, let i = visible.firstIndex(where: { $0.uid == pinned }) {80 out.append(item(for: visible.remove(at: i)))81 }82 guard !visible.isEmpty else { return out }83 if visible.count <= singleThreshold { return out + visible.map(item(for:)) }8485 let cols = max(2, columns)86 let rows = max(2, Int((Double(cols) * aspect).rounded()))87 // grille ancrée sur des multiples de la maille : les regroupements ne sautent pas quand la carte glisse88 let cw = w / Double(cols), ch = h / Double(rows)8990 struct Acc { var n = 0; var positions = 0; var sumLat = 0.0; var sumLng = 0.0; var minPrice: Double?; var first: MapPoint? }91 var cells: [Int64: Acc] = [:]92 for p in visible {93 let cx = Int64((p.lng / cw).rounded(.down)), cy = Int64((p.lat / ch).rounded(.down))94 let key = cx &* 1_000_003 &+ cy95 var a = cells[key] ?? Acc()96 let weight = Double(max(p.n, 1))97 a.n += max(p.n, 1); a.positions += 198 a.sumLat += p.lat * weight; a.sumLng += p.lng * weight99 if let pr = p.priceMin { a.minPrice = min(a.minPrice ?? pr, pr) }100 if a.first == nil { a.first = p }101 cells[key] = a102 }103104 // fusion des cellules voisines dont les centres sont trop proches : les plaques ne se chevauchent pas105 var accs = cells.values.sorted { $0.n > $1.n }106 var merged: [Acc] = []107 let minDist = 0.8108 while !accs.isEmpty {109 var a = accs.removeFirst()110 var again = true111 while again {112 again = false113 let cLat = a.sumLat / Double(a.n), cLng = a.sumLng / Double(a.n)114 var rest: [Acc] = []115 for b in accs {116 let dx = (b.sumLng / Double(b.n) - cLng) / cw, dy = (b.sumLat / Double(b.n) - cLat) / ch117 if dx * dx + dy * dy < minDist * minDist {118 a.n += b.n; a.positions += b.positions; a.sumLat += b.sumLat; a.sumLng += b.sumLng119 if let m = b.minPrice { a.minPrice = min(a.minPrice ?? m, m) }120 again = true121 } else {122 rest.append(b)123 }124 }125 accs = rest126 }127 merged.append(a)128 }129130 for a in merged {131 if a.positions == 1, let p = a.first {132 out.append(item(for: p))133 } else {134 let lat = a.sumLat / Double(a.n), lng = a.sumLng / Double(a.n)135 let key = "\(Int64((lng / cw).rounded(.down)))_\(Int64((lat / ch).rounded(.down)))"136 out.append(MapItem(id: "c\(key)-\(a.n)", lat: lat, lng: lng, kind: .cluster(count: a.n, minPrice: a.minPrice)))137 }138 }139 if out.count > maxItems {140 out.sort { $0.count > $1.count }141 out = Array(out.prefix(maxItems))142 }143 return out144 }145146 /// Zone englobante robuste, pondérée par le nombre de véhicules : elle contient 92 % des véhicules (4 % écartés147 /// de chaque côté), pour que quelques annonces éloignées ne fassent pas reculer toute la carte.148 static func robustBounds(_ points: [MapPoint]) -> MapBounds? {149 guard !points.isEmpty else { return nil }150 let total = points.reduce(0) { $0 + max($1.n, 1) }151 func range(_ key: (MapPoint) -> Double) -> (Double, Double) {152 let sorted = points.sorted { key($0) < key($1) }153 let cut = total > 40 ? Double(total) * 0.04 : 0154 var acc = 0.0, lo = key(sorted[0]), hi = key(sorted[sorted.count - 1])155 for p in sorted { acc += Double(max(p.n, 1)); if acc > cut { lo = key(p); break } }156 acc = 0157 for p in sorted.reversed() { acc += Double(max(p.n, 1)); if acc > cut { hi = key(p); break } }158 return (min(lo, hi), max(lo, hi))159 }160 let (w, e) = range(\.lng), (s, n) = range(\.lat)161 var b = MapBounds(west: w, south: s, east: e, north: n)162 // une seule position : une zone de quelques kilomètres autour163 if b.east - b.west < 0.02 { b.west -= 0.04; b.east += 0.04 }164 if b.north - b.south < 0.02 { b.south -= 0.03; b.north += 0.03 }165 return b166 }167}168