The map shows a crisp blue dot. The app receives a latitude and a longitude with six decimal places, which is a resolution of about eleven centimeters.
Neither of those means the device is there.
A location is an observation: something a set of radios and sensors estimated, at a particular moment, with a particular uncertainty. Core Location reports that uncertainty with every sample. Most bugs in location features come from the first line of code that throws it away, usually a mapper that converts CLLocation into a struct holding two Doubles.
After that line, the rest of the app treats an estimate as a fact. The symptoms are familiar to anyone who has shipped a location feature: a courier who "arrived" while still across the street, a run recorded at 140 km/h for two seconds, a geofence that enters and exits six times in a minute, a route that crosses a river where there is no bridge.
Keep the evidence with the value
The domain type should carry what the app will later need to judge the sample:
import Foundation
struct LocationObservation: Equatable, Sendable {
let latitude: Double
let longitude: Double
let horizontalAccuracyMeters: Double
let observedAt: Date
let receivedAt: Date
let source: Source
enum Source: String, Sendable {
case coreLocation
case importedTrack
case userSelected
}
}horizontalAccuracyMeters is the radius of uncertainty around the coordinate. A value of 65 means the device is probably within 65 meters of the reported point. The dot on the map is the center of that circle, and the circle is the measurement.
observedAt and receivedAt are separate on purpose. Core Location can deliver a cached fix immediately when updates start, and that fix may be minutes old. A sample that arrives now can describe where the device was before the user got on a train.
source is the app's own classification. It distinguishes a system fix from a point in an imported GPX file and from a pin the user dropped. It does not claim to know which radio produced a sample; Core Location does not expose that.
The adapter that produces this type is where Core Location's conventions are translated, once:
import CoreLocation
extension LocationObservation {
init?(_ location: CLLocation, receivedAt: Date) {
guard location.horizontalAccuracy >= 0,
CLLocationCoordinate2DIsValid(location.coordinate) else {
return nil
}
self.init(
latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
horizontalAccuracyMeters: location.horizontalAccuracy,
observedAt: location.timestamp,
receivedAt: receivedAt,
source: .coreLocation
)
}
}Core Location uses negative numbers to mean "invalid": a negative horizontalAccuracy means the coordinate itself is unusable, and negative speed or course mean those fields were not measured. Code that reads location.speed without checking the sign will, sooner or later, compute with −1 meters per second. Handle the sentinel values in the adapter so the rest of the app only sees optionals and valid numbers.
Two more fields are routinely misread. course is the direction of travel over the ground, not the direction the phone is pointing; a pedestrian walking north while looking at a phone held sideways has a course of north. Device orientation comes from heading, a different API with its own accuracy. And sourceInformation, which reports whether a location was simulated or produced by an external accessory, is useful for diagnostics and is not a spoofing defense. A server must never authorize something valuable only because an unverified client says it is nearby.
Valid is not the same as suitable
A sample can be a perfectly valid coordinate and still be the wrong input for a decision. An accuracy of 1,500 meters is enough to choose a city for a weather forecast. It cannot tell you which entrance of a building the user reached.
So suitability is a policy, stated per use:
struct LocationPolicy: Sendable {
let maximumAge: TimeInterval
let maximumAccuracyMeters: Double
let allowedFutureSkew: TimeInterval
func accepts(
_ observation: LocationObservation,
now: Date
) -> Bool {
guard maximumAge.isFinite, maximumAge >= 0,
maximumAccuracyMeters.isFinite,
maximumAccuracyMeters >= 0,
allowedFutureSkew.isFinite,
allowedFutureSkew >= 0 else {
return false
}
guard observation.latitude.isFinite,
observation.longitude.isFinite,
observation.horizontalAccuracyMeters.isFinite,
(-90...90).contains(observation.latitude),
(-180...180).contains(observation.longitude),
observation.horizontalAccuracyMeters >= 0,
observation.horizontalAccuracyMeters
<= maximumAccuracyMeters else {
return false
}
let age = now.timeIntervalSince(observation.observedAt)
return age.isFinite
&& age >= -allowedFutureSkew
&& age <= maximumAge
}
}The thresholds are parameters because no universal value exists. "Nearby restaurants" might accept five minutes and 500 meters. "Confirm delivery at the door" might want ten seconds and 20 meters. Two features in the same app should have two policies, and the numbers should come from recorded traces of the real environment.
The isFinite checks look paranoid until an imported track file contains NaN. Every comparison with NaN is false, so a guard written as accuracy > maximum → reject lets it through. The policy also bounds how far in the future a timestamp may be: clocks drift, and imported data carries whatever its source wrote.
This is an admission filter and nothing more. It does not smooth, it does not detect spoofing, and it does not prove the device is inside the reported circle.
Distance between two estimates is an estimate
The distance between two reported coordinates is arithmetic on two uncertain numbers. If each sample has an accuracy of 30 meters, a computed displacement of 12 meters does not show that anyone moved. The device may have been on a desk the whole time, with the estimate wandering inside its circle.
Derived speed makes it worse. Divide that 12 meters of noise by a one-second interval and the app reports 43 km/h. This is the mechanism behind impossible speeds in activity trackers, and it is why I only derive a rate when the displacement is larger than the combined uncertainty:
func longitudeDelta(from start: Double, to end: Double) -> Double {
var delta = (end - start).truncatingRemainder(dividingBy: 360)
if delta > 180 { delta -= 360 }
if delta <= -180 { delta += 360 }
return delta
}
func distanceMeters(
from a: LocationObservation,
to b: LocationObservation
) -> Double {
let earthRadius = 6_371_008.8
let lat1 = a.latitude * .pi / 180
let lat2 = b.latitude * .pi / 180
let dLat = lat2 - lat1
let dLon = longitudeDelta(from: a.longitude, to: b.longitude) * .pi / 180
let h = sin(dLat / 2) * sin(dLat / 2)
+ cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2)
return 2 * earthRadius * asin(min(1, h.squareRoot()))
}
func impliedSpeed(
from earlier: LocationObservation,
to later: LocationObservation
) -> Double? {
let interval = later.observedAt.timeIntervalSince(earlier.observedAt)
guard interval > 0 else { return nil }
let distance = distanceMeters(from: earlier, to: later)
let uncertainty = earlier.horizontalAccuracyMeters
+ later.horizontalAccuracyMeters
guard distance > uncertainty else { return nil }
return distance / interval
}Returning nil is the honest answer when the evidence cannot support a number. The interval check also catches duplicate and out-of-order samples, which do arrive, and which otherwise produce a division by zero or a negative speed.
When the platform reports a valid speed, prefer it; it is derived from Doppler measurements and is usually far better than differencing positions. The function above is for the cases where you only have positions, such as imported tracks.
Filtering deserves the same caution. A smoothing filter makes a track look better on a map. It also rounds off real corners and can drag the line through buildings. Choose a filter for the use case, and validate it against recorded traces where you know what actually happened. A smooth line is not automatically a more accurate one.
Use hysteresis for decisions at a boundary
The naive arrival rule is "within 30 meters means arrived, otherwise not". A user standing 28 meters away with 15 meters of noise will cross that line repeatedly without moving. Each crossing triggers a notification, an API call, or a state change that the rest of the system treats as real.
Three ingredients make the decision stable: different radii for entering and leaving, a requirement that the uncertainty circle is entirely on one side, and several consecutive samples in agreement.
struct ArrivalDetector: Sendable {
enum State: Equatable, Sendable {
case undetermined, arrived, away
}
let enterRadius: Double
let exitRadius: Double
let requiredSamples: Int
private(set) var state: State = .undetermined
private var candidate: State?
private var streak = 0
init(enterRadius: Double, exitRadius: Double, requiredSamples: Int) {
precondition(exitRadius > enterRadius && requiredSamples > 0)
self.enterRadius = enterRadius
self.exitRadius = exitRadius
self.requiredSamples = requiredSamples
}
mutating func ingest(distance: Double, accuracy: Double) -> State {
let evidence: State?
if distance + accuracy <= enterRadius {
evidence = .arrived
} else if distance - accuracy >= exitRadius {
evidence = .away
} else {
evidence = nil
}
guard let evidence, evidence != state else {
candidate = nil
streak = 0
return state
}
streak = (candidate == evidence) ? streak + 1 : 1
candidate = evidence
if streak >= requiredSamples {
state = evidence
candidate = nil
streak = 0
}
return state
}
}A sample whose circle straddles either boundary is treated as no evidence. It does not change the state and it resets the count, so three clean samples are needed in a row.
The initial state is .undetermined, and it stays that way until the evidence is good enough. That third value is the point of the design. With only arrived and not-arrived available, the app has to assert one of them when it knows neither, and the UI then displays a confidence the data never had. For a high-consequence decision such as releasing a payment or marking a delivery complete, "we can't tell yet; tap to confirm" is a correct product state.
The radii and the sample count are product parameters. Dense city streets, an open car park, and the inside of a shopping center need different values, so choose them from traces recorded in those places. Numbers copied from a tutorial were tuned for somewhere else.
Coordinate systems change at boundaries
Latitude and longitude are angles on a model of the Earth. Screen points, map-projection units, and the local meters of an AR session are different spaces, and none of them converts to another by a constant factor.
A degree of longitude is about 111 km at the equator and about 56 km at 60° north. Code that multiplies degrees by a fixed number to get meters or pixels is wrong everywhere except the latitude it was tested at. Use the framework's conversions: MKMapPoint and the map view's convert methods for maps, and CLLocation.distance(from:) or an equivalent great-circle calculation for distances.
Altitude needs the same explicitness. CLLocation.altitude is height above mean sea level, and ellipsoidalAltitude is height above the reference ellipsoid. Neither is zero at the floor of a room where an AR session started.
Then there is the antimeridian. Longitudes 179.9 and −179.9 are 0.2 degrees apart, and a naive subtraction says 359.8. Every bounding box, midpoint, and "is this point between those two" check written with plain subtraction breaks for users in Fiji, eastern Russia, and on any flight across the Pacific. The longitudeDelta function above is the fix, and a test with one point on each side of the line belongs in every location codebase.
Privacy is part of the data model
A location history reveals where someone lives, where they work, who they visit, and when they see a doctor. That makes retention and precision design decisions about the data model, with the same weight as its field types.
Collect at the precision the feature needs. If a city is enough, ask for reduced accuracy and store a coarse value. Separate an ephemeral query ("what's nearby right now") from a durable history, because they have different retention rules. Remember that the user can grant approximate location only: with accuracyAuthorization == .reducedAccuracy, the app receives a region several kilometers across, and a feature that silently assumes precise fixes will make confident, wrong statements.
Location also leaks through side channels the data model does not show: a screenshot of a route, EXIF data in a photo attached to a support ticket, coordinates in a debug log. Being authorized to read location does not make every downstream use appropriate, and each export path needs its own decision.
Test with traces
A unit test with one coordinate tests almost nothing here. A useful fixture is a sequence: timestamp, coordinate, accuracy, and the decision the domain should make after each sample.
Include the cases that occur in the field:
- a cached fix several minutes old delivered first;
- two samples with the same timestamp, and one that arrives out of order;
- an invalid (negative) accuracy;
- a stationary device indoors with 40 meters of wander;
- a walk along the edge of the arrival radius;
- a pair of points on either side of the antimeridian;
- a switch from precise to approximate authorization mid-trace.
Use synthetic traces for deterministic tests and recorded ones for validation on real hardware, and record which is which, so that nobody later mistakes a simulated result for field evidence.
The assertion I value most in these suites is "after this sequence the state is still undetermined". Withholding a decision because the evidence was insufficient is correct behavior, and it should have a test that keeps it that way.
What to ask of your own app
- Where does accuracy get dropped between
CLLocationand the code that makes decisions? - Is
speed,course, orhorizontalAccuracyever read without checking for a negative value? - Does each location-based decision have its own stated age and accuracy policy?
- Can any boundary decision change state on a single sample?
- What does each feature do when the user grants approximate location only?
A coordinate is useful evidence. The architecture has to keep enough of that evidence to know when it supports the statement the product is about to make.
References
- Core Location: CLLocation
- Core Location: horizontalAccuracy
- Core Location: CLAccuracyAuthorization
- Core Location: Requesting authorization to use location services
- MapKit: MKMapPoint
Related editions
- Edition 37 · MapKit Is Not Just a Map
- Edition 35 · Core Bluetooth in Production: From Connection to a Live Reading
- Edition 18 · Your App Is Showing the Truth. Just Not the Current One.
If this edition sharpened your next review, you can buy me a coffee.