SwiftUI Maps & Location: Fundamentals

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

Part 2: Core Location

17. Geocode an Address

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: 16. Update in the Background Next episode: 18. Challenge: Find a Location

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: 17. Geocode an Address

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.

Geocoding is process of converting addresses into coordinates and coordinates into addresses. To do this, we use an object called the CLGeocoder.

Demo

To get started, open up your demo sample app. Our app has an issue. It doesn’t display the addresses of all the various locations. All we have is a latitude and longitude coordinate. This won’t be a problem. Open up your LocationManager.swift. We’ll start by adding a current addresses property.

@Published var currentAddress = ""
lazy var geocoder = CLGeocoder()
func fetchAddress(for place: Place) {

}
currentAddress = ""
geocoder.reverseGeocodeLocation(place.location) { [weak self] placemarks, error in

}
if let error = error {
    fatalError(error.localizedDescription)
}
guard let placemark = placemarks?.first else { return }
if let streetNumber = placemark.subThoroughfare,
   let street = placemark.thoroughfare,
   let city = placemark.locality,
   let state = placemark.administrativeArea {
        self?.currentAddress = "\(streetNumber) \(street) \(city), \(state)"
}
else if let city = placemark.locality, let state = placemark.administrativeArea {
    self.currentAddress = "\(city), \(state)"
}
else {
    self.currentAddress = "Address Unknown"
}
@StateObject private var locationManager = LocationManager()
@ObservedObject var locationManager: LocationManager
@ObservedObject var locationManager: LocationManager
PlacesView(places: places, selectedPlace: $selectedPlace, locationManager: locationManager)
OtherPlacesScrollView(selectedPlace: $selectedPlace, locationManager: locationManager, places: places)
  @Binding var selectedPlace: Place {
    didSet {
      locationManager.fetchAddress(for: selectedPlace)
    }
  }
    .onAppear {
      locationManager.fetchAddress(for: place)
    }
Text(locationManager.currentAddress)