Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve user current location using SwiftUI and MapKit

I would like to know how to get the user current location using SwiftUI Framework. I have the map displaying already but I want to know how to get the user latitude and longitude of current location. Feel free to create a class but please explain the class actions and where to implement it. By having the map to display already is by using the UIViewRepresentable and the two functions called makeUIView and updateUIView Thank you in advance

like image 941
JosieGPT Avatar asked Oct 15 '25 14:10

JosieGPT


1 Answers

Create instance of CLLocationManager:

var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()

then get the details:

var currentLocation: CLLocation!

if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() ==  .authorizedAlways){

  currentLocation = locManager.location

}

then to get longitude or latitude:

let longitude = currentLocation.coordinate.longitude
let latitude = currentLocation.coordinate.latitude

If you'd like to perform it inside a swiftUI view script, create instance:

@ObservedObject var locationManager = LocationManager()

Get them separately:

var userLatitude: String {
    return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"

var userLongitude: String {
        return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
like image 118
Nathan Avatar answered Oct 17 '25 06:10

Nathan