iosswiftgpscore-location

CoreLocation returning cached location as new and accurate when underground


I'm working on a Swift App that collects the location of the user as they use it. Sometimes the user will be underground where there is no GPS/other location fixing signal available. Thats fine and the app should simply not return a location in this case, but for some reason it still is returning the last location fix that it got, even though I am trying to filter those old locations out. Im using this to feed an output that shows the location (formatted) and that stays on the old location even though its been minutes since the last succesful update was. Apple Maps and Google Maps also still show the old location as blue dots on the map (so as non cached (afaik)).

// Delegate method called when location is updated
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Get the most recent location
        guard let location = locations.last else { return }

        // Define a threshold for the location age
        let maximumAge: TimeInterval = 15
        let now = Date()
        let isRecent = now.timeIntervalSince(location.timestamp) <= maximumAge
        let isAccurateHorizontal = location.horizontalAccuracy <= self.demandedAccuracy
        let isAccurateVertical = location.verticalAccuracy <= self.demandedAccuracy
        
        print("Raw: \(location)")

        if isRecent && isAccurateHorizontal && isAccurateVertical {
            queryLocation(to: location, appendVisited: true)
            print(location)
            print("Filtered: \(location)")
        }
    }

Above is the code that i have as my locationManager delegate. It filters out any locations that are older than 15 seconds as well as any where the accuracy (I'm thinking horizontal would be enough but better safe than sorry) is below a variable amount set elsewhere. From running the app in the subway where there is obviously no accurate location signal it showed highly inaccurate (400m+) readings so I added the distance filter but for some reason even this isn't enough to prevent this ghosting of the last locations. Im thinking it might be impossible because both Apple and Google Maps face the same issue seemingly but I don't understand why as IMO the timestamp filter should prevent too much caching.


Solution

  • I faced the same problem and used out-of-date timestamps to filter out cached locations. That solution worked for me.

    Check the math on your date check code, and log the timestamp you are getting. (using DateFormatter.localizedString(from:dateStyle:timeStyle:) so it is in your local time zone.)