Detecting Bad CoreLocation Data

CoreLocation can (and will) give you poor location data. Over the course of developing RunMonster, I have become painfully aware of this fact. It turns out, though, that you can detect and discard the most egregiously bad location data using a few simple tests.

When a new point comes in, it is invalid and can be discarded if it matches any of the following criteria:

  • The location is nil.
  • The location’s horizontalAccuracy is < 0.
  • The timestamp of the new location is earlier than the timestamp of the previous location, indicating the points came in out of order.
  • The timestamp of the new location is set to a time before your app was even initialized.

In regards to the last bullet, the CoreLocation framework seems to cache and report points from the last time the GPS unit was used. For instance, if you last ran the GPS in Montana and then open your app in Georgia, the first point could be the last cached point from Montana. If you are running a distance-tracking application, then your app would merrily add thousands of miles to your total distance.

The Code

The helper method below checks for these four cases to determine if the newly reported location is valid or not:

- (BOOL)isValidLocation:(CLLocation *)newLocation
    withOldLocation:(CLLocation *)oldLocation
    // Filter out nil locations
    if (!newLocation)
        return NO;
    // Filter out points by invalid accuracy
    if (newLocation.horizontalAccuracy < 0)
        return NO;
    // Filter out points that are out of order
    NSTimeInterval secondsSinceLastPoint =
        [newLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
    if (secondsSinceLastPoint < 0)
        return NO;
    // Filter out points created before the manager was initialized
    NSTimeInterval secondsSinceManagerStarted =
        [newLocation.timestamp timeIntervalSinceDate:locationManagerStartDate];
    if (secondsSinceManagerStarted < 0)
        return NO;
    // The newLocation is good to use
    return YES;

locationManagerStartDate is an NSDate that records when the CLLocationManager is initialized:

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

locationManagerStartDate = [[NSDate date] retain];

That’s a Wrap

If you are developing any kind of distance-tracking application that uses the phone’s GPS, you should definitely consider using the filters above. These particular error cases were discovered through trial and error, and as Apple improves CoreLocation, they may very well fix these problems. However, these filters have helped RunMonster avoid the wacky GPS issues that plague many distance-tracking applications.

77 Responses to “Detecting Bad CoreLocation Data”

  1. Hi Troy,

    as always, another great blog post! But are you sure that points, that are not in order should be filtered out? The iPhone Application Programming Guide says in chapter 8 “Getting the User’s Current Location”:

    “Note: The Core Location framework records timestamp values at the beginning of each location query, not when that query returns. Because Core Location uses several different techniques to get a location fix, queries can sometimes come back in a different order than their timestamps might otherwise indicate. As a result, it is normal for new events to sometimes have timestamps that are slightly older than those from previous events. The framework concentrates on improving the accuracy of the location data with each new event it delivers, regardless of the timestamp values.”

    Greetings from Germany,

  2. You have tested it and writing form your personal experience or you find some information online?

  3. nice post. thanks.

  4. I think I can take this information one step further. You should not just ignore but blacklist any points that appear out of order, and then drop any further references to that exact location: that seems clear out the repeated jumps to a specific point I see quite often.

  5. Hey Troy,
    RunMonster, app looks awesome congrats.
    I’m working on some app which is working wich is needed turn by turn correct gps data. Let me ask you a question, what is the runmonster’s CLLocationManager intialize values ?
    .desiredAccuracy = ?
    .distanceFilter = ?

    or what is your suggestion ?


  6. Hi,

    Nice tips, and a nice app you got there in appstore, I was wondering what methods you used to draw the routes over the map? Can you try to write a blogpost about it aswell?

    Thanks ;-)

  7. Dude, you really have to check your Comments more often! In case you missed my comment, here’s the lowdown.In recent months, this crazy dude has been doing the exact OPPOSITE of what everybody else in “Internet Marketing” has beendoing, and it’s proven to be a more profitable approach than anything I’ve ever seen before , watch this video BUZZBOOZ.COM The good part starts somewhere around the 2 minute mark.

  8. Hello there! This blog post couldn’t be written much better! Looking at this post reminds me of my previous roommate! He continually kept preaching about this. I am going to forward this information to him. Pretty sure he’ll have a great read.
    Thanks for sharing!

  9. I was more than happy to find this great site. I wanted to thank you for ones time due
    to this fantastic read!! I definitely really liked every little bit of it and i also
    have you saved as a favorite to check out new things on your blog.

  10. I am really impressed with your writing abilities and also with the
    layout to your blog. Is this a paid subject or did you customize
    it yourself? Anyway keep up the nice quality writing,
    it is rare to see a nice weblog like this one these days..

  11. Simply wish to say your article is as astonishing.

    The clarity on your submit is just nice and i could suppose you’re an expert in
    this subject. Fine along with your permission let me
    to seize your feed to stay updated with imminent post.
    Thank you 1,000,000 and please carry on the gratifying work.

  12. Do you mind if I quote a few of your articles
    as long as I provide credit and sources back to your website?

    My blog site is in the exact same niche as yours and my visitors would definitely benefit from a lot of the information you present here.
    Please let me know if this okay with you. Regards!

  13. Hiya! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest
    authoring a blog article or vice-versa? My site discusses a
    lot of the same topics as yours and I believe we could greatly benefit from each
    other. If you happen to be interested feel free to send me an e-mail.

    I look forward to hearing from you! Wonderful blog by the way!

  14. Hello, I log on to your blogs named “Detecting Bad CoreLocation Data” daily.

  15. Symptoms may include eye pain, fever, asthma, rashes and intestinal cramping.
    The mother will nurse them for 3-4 months
    until they are able to swim on their own. When insurance companies stress preventive health, they always emphasize doctor exams over laboratory

  16. I wanted to draft you the little observation just to give many thanks as before over the breathtaking guidelines you have discussed in this case. This is really generous of you in giving easily precisely what numerous people could have supplied for an e book in order to make some profit for themselves, primarily seeing that you might have tried it if you ever considered necessary. The guidelines also served to become good way to fully grasp the rest have a similar eagerness just like mine to understand a whole lot more with regards to this condition. I am sure there are some more fun instances ahead for folks who looked at your blog.

  17. I am continually looking online for articles that can benefit me. Thx!

  18. You made some good points there. I did a search on the subject matter and found most people will agree with your website.

  19. Magnificent web site. A lot of useful information here. I¡¦m sending it to a few friends ans also sharing in delicious. And certainly, thank you for your effort!

  20. This has to be my 2nd favorite piece of writing of the week, i can’t inform
    you the very best, it might offend you!

  21. you’re actually a good webmaster. The web site loading velocity is amazing. It sort of feels that you are doing any distinctive trick. Also, The contents are masterpiece. you’ve performed a wonderful activity in this subject!

  22. I appreciate, result in I discovered exactly what I was having a look for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  23. As I web-site possessor I believe the content material here is rattling fantastic , appreciate it for your efforts. You should keep it up forever! Good Luck.

  24. Quality posts is the important to be a focus for the people to pay a
    visit the site, that’s what this web site is providing.

  25. I抦 impressed, I have to admit. Rarely do I come across a blog that抯 both equally educative and amusing, and let me tell you, you have hit the nail on the head. The problem is something which not enough folks are speaking intelligently about. I am very happy that I came across this in my search for something concerning this.

  26. Saved like a favourite, excellent internet site!

  27. Lovely blog, it loads genuinely fast and appears really awesome.

  28. Impressive Piece of writing

  29. The findings by Chicago based Navigant Consulting were a follow up to previously noted concerns that New Jersey Department of Community Affairs, distributor of most federal disaster aid, was not thoroughly vetting contractors involved in the the Reconstruction, Rehabilitation, Elevation, and Mitigation (RREM) program.

  30. He also had an outstanding federal warrant for felon in possession of a firearm.

  31. great points altogether, you just won a brand new reader. What might you recommend in regards to your put up that you made a few days ago? Any certain?

  32. Well I sincerely liked reading it. This subject provided by you is very helpful for good planning.

  33. hey there and thank you for your information – I’ve definitely picked up something new from right here. I did however expertise a few technical issues using this web site, since I experienced to reload the website many times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Ensure that you update this again very soon..

  34. Thank you for any other fantastic article. Where else could anyone get that type of info in such an ideal way of writing? I have a presentation next week, and I am at the look for such information.

  35. District Attorney George Brauchler has said Holmes’ breakup with Datta was a catalyst to the shooting during a midnight premiere of a Batman movie. Datta was Holmes’ first romantic relationship, and he had told her he loved her. She told him she cared about him only as a friend.

  36. I wanted to create you this little bit of remark so as to thank you the moment again for these pleasing information you’ve featured on this site. It was so remarkably open-handed of people like you to give openly what exactly many people could have marketed as an electronic book to help with making some dough on their own, particularly considering the fact that you could possibly have tried it if you ever wanted. The secrets in addition acted to become great way to fully grasp other people online have the same interest the same as my very own to know the truth lots more pertaining to this matter. I am sure there are numerous more fun instances up front for individuals who check out your blog post.

  37. I savour, result in I discovered just what I was taking a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  38. I have been reading out some of your articles and i must say pretty good stuff. I will make sure to bookmark your website.

  39. As a Newbie, I am permanently browsing online for articles that can be of assistance to me. Thank you

  40. I have been reading out some of your posts and it’s pretty nice stuff. I will make sure to bookmark your site.

  41. Great remarkable issues here. I¡¦m very satisfied to peer your article. Thank you a lot and i’m looking forward to touch you. Will you please drop me a mail?

  42. I’ve just bookmarked this page, excellent internet

  43. This is very good post i will link this post to my blog, keep posting!

  44. Coño Mazi que internacional eres jajaja…Por cierto, mola el superman… ahora haz uno del capi que nos gusta mucho a los dos… jeje

  45. Many animals that eat fish and other live aquatic prey have these nodules in their They are slightly pointed back towards their This prevents fish from squirming their way back out while being

  46. ¡Buen día! Soy consciente de que es el tipo de fuera de tema una vez dicho esto me preguntaba qué plataforma de blogs han estado usando para este sitio web?
    Me estoy harto de WordPress porque he tenido problemas con los hackers y estoy comprobando hacia fuera las opciones para una más plataforma.
    yo personalmente ser fantástico en el caso de que usted podría apuntar
    me hacia una buena plataforma.

  47. This is the perfect blog for anybody who would like to understand this topic.
    You know a whole lot its almost hard to argue
    with you (not that I actually will need to…HaHa).
    You definitely put a new spin on a subject that has been discussed for a
    long time. Great stuff, just wonderful!

  48. Hi there, You have done a fantastic job. I will definitely digg it and personally suggest to my friends. I’m sure they’ll be benefited from this web site.

  49. Somos una empresa especializada en reparación de calderas Junkers, calentadores Junkers, termos Junkers, instalación de calderas Junkers,calentadores Junkers y termos Junkers, con muchos años de experiencia, dedicándonos a la asistencia técnica a domicilio, siendo nuestros clientes tanto particulares como empresas, comunidades de vecinos instituciones oficiales.

  50. El fruto de 35 años de experiencia en el sector de la calefacción,climatización, y saneamiento avala a esta empresa en Segovia, que al mismo tiempo se mantiene al tanto de las últimas novedades y técnicas pioneras como la telegestión la geotermia. REPARACIÓN MANTENIMIENTO E INSTALACIÓN de calderas de gasoil y gas, acumuladores de agua y termos, descalificadores y osmosis para el tratamiento de agua contra la cal y instalaciones de placas solares para acumulaciones de agua climatizaciones de piscinas. Somos Frío Jerez, S.L., una empresa especializada en la venta de aire acondicionado. Desde el inicio de labores, en el año 1985, nuestro esfuerzo se ha basado en mejorar los servicios que ofrecemos, con calidad y eficiencia.

Leave a Reply