SwiftUI Maps & Location: Fundamentals

Mar 15 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: Core Location

15. Challenge: Determine Distance

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 14. Request Permission Next episode: 16. Update in the Background

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 15. Challenge: Determine Distance

The student materials have been reviewed and are updated as of January, 2022.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Determining the distance between two places is something that Core Location provides right out of the box. You just need two things. You need a start location and then you need an end location. And that’s what you’ll be doing in this challenge. Your challenge is calculate the distance from your current location to one of the interesting places. Print out the distance on the location distance UILabel.

Challenge

To do this, you’ll need to get the start location of the user and then when they tap on a location, you’ll need to get the distance from that location. You’ll do this using the distance method on CLLocation. This returns the distance in meters between another location. Once you have your location, you can either use it or do a simple conversion.

Solution

How’d that challenge go for you. If you got stuck, don’t worry about it. Learning an APi takes both time and practice and getting stuck is part of the process. Okay, so open your project from when you last worked on it. Open up the location manager.

var previousLocation: CLLocation?
if previousLocation == nil {
    previousLocation = latest
}
else {
    let distanceInMeters = previousLocation?.distance(from: latest) ?? 0
}
previousLocation = latest
locationString = "You are \(Int(distanceInMeters)) meters from your start point."