Reputation: 127
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
Upvotes: 3
Views: 4702
Reputation: 1762
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)"
Upvotes: 4