Leave a rating/review
Notes: 15. Challenge: Determine Distance
The student materials have been reviewed and are updated as of January, 2022.
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.
To convert the distance from meters to feet or some other measurement, you could do a quick google search for the math, or you could use the Measurement class. This is a class that was included in iOS 10 which includes and the methods necessary to convert your measurements into different distances.
You simply pass in the distance as the value, and designate the type of distance it is. After which, you call the converted method, specifying the distance you want it converted to. Take this challenge one piece at a time. Now pause the video and try it out. When you’re ready, unpause and see how you did.
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.
We want to calculate the distance from one location to another. To do this, we need to keep track of our past location. Open up LocationManager.swift. Let’s create a property for our previous location. This will be a CLLocation.
var previousLocation: CLLocation?
When we first receive a location, we’ll populate it. Let’s do this in didUpdateLocations underneath the guard statement.
if previousLocation == nil {
previousLocation = latest
}
Now we will calculate the distance in the else branch. Each location has a distance method that takes in another location. Add the following:
else {
let distanceInMeters = previousLocation?.distance(from: latest) ?? 0
}
If the previous location has a nil value then the distance will be zero meters. Now, we’ll update the previous location.
previousLocation = latest
And finally, we’ll print out the locationString to show the distance.
locationString = "You are \(Int(distanceInMeters)) meters from your start point."
Now build and run. Make sure the simulator is set to a freeway drive and start location services. You’ll see that we get updates. Well done.