I'm new to iOS and am building a very simple iOS using swift 5.7.2 and XCode 14.2.
The app basically needs to show a Google Map View as the user's device travels around. I have successfully made the view and enabled location service and the Map now shows my location on the map. The blue icon also tracks my location as I move around.
However, even though the blue icon representing my position moves around, the map itself doesn't move around and that can result in my position being outside of the map if I have travelled far enough.
My UIViewController is:
import UIKit
import AVKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager?.delegate = self
manager?.desiredAccuracy = kCLLocationAccuracyBest
manager?.requestAlwaysAuthorization()
manager?.startUpdatingLocation()
let currentCoordinate = manager?.location?.coordinate
let viewBounds = self.view.bounds
let screenCenter = CGPoint(x: viewBounds.midX, y: viewBounds.midY)
let camera = GMSCameraPosition.camera(withLatitude: currentCoordinate?.latitude ?? 51.0447, longitude: currentCoordinate?.longitude ?? -114.0719, zoom: 9.0)
let navView = GMSMapView.map(withFrame: CGRect(x: 130, y: 10, width: viewBounds.maxX - 135 * 2, height: viewBounds.maxY - 20), camera: camera)
navView.isMyLocationEnabled = true
self.view.addSubview(navView)
}
}
What I think is wrong:
I am not using didUpdateLocations
of locationManager
to update the camera position as I am not sure what's the proper way of doing it. Throwing this code inside UIViewController
doesn't work:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue:CLLocationCoordinate2D = manager.location!.coordinate
print(locValue)
}
What's the proper way of doing it?
Thanks!
The signature is wrong (it's Swift 2 outdated for a long time).
Please have a look at a the documentation, the current signature is
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last!
print(location.coordinate)
}
and the updated locations are in the locations
parameter.
And to avoid the optional replace
var manager: CLLocationManager?
with
let manager = CLLocationManager()
and remove manager = CLLocationManager()
and the question marks