Geek Culture
Published in

Geek Culture

Working with details of location in Swift

Photo by Clay Banks on Unsplash

Fetching details based on coordinates

func update() {let latitude = location?.latitude ?? 0let longitude = location?.longitude ?? 0self.region = MKCoordinateRegion(center:CLLocationCoordinate2D(latitude:                                                                       CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude)), span:                                 MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { placemarks, error inguard let placemark = placemarks?.first else {return}let reversedGeoLocation = GeoLocation(with: placemark)
self.name = reversedGeoLocation.name

}

}
struct GeoLocation {let name: Stringlet streetName: Stringlet city: Stringlet state: Stringlet zipCode: Stringlet country: Stringinit(with placemark: CLPlacemark) {self.name           = placemark.name ?? ""self.streetName     = placemark.thoroughfare ?? ""self.city           = placemark.locality ?? ""self.state          = placemark.administrativeArea ?? ""self.zipCode        = placemark.postalCode ?? ""self.country        = placemark.country ?? ""}}

Fetching Coordinates based on Address

func reverseUpdate() {let geocoder = CLGeocoder()geocoder.geocodeAddressString(name) { placemarks, error in

guard error == nil else { return}

guard let placemark = placemarks?[0] else {return}
let coord = placemark.location?.coordinate ?? CLLocationCoordinate2D(latitude:
CLLocationDegrees(0), longitude: CLLocationDegrees(0))
self.region = MKCoordinateRegion(center: coord, span:
MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
self.location = CLLocationCoordinate2D(latitude: placemark.location?.coordinate.latitude ?? 0, longitude: placemark.location?.coordinate.longitude ?? 0)

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sai Durga Mahesh

Using Data Science to provide better solutions to real word problems