skyleguy skyleguy - 3 months ago 14
Swift Question

update center of screen with current location

I have successfully made an app that shows a blinking blue dot where the user currently is. However as of right now the center of the screen does not follow the blue dot as the user moves, so if the user moves the blue dot just exits the screen and the user would have to scroll to keep up with it. That isnt user friendly! I have the below code:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var map: MKMapView!

let locationManager = CLLocationManager()
var mapp = MKMapView.self

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
if (CLLocationManager.locationServicesEnabled())
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation() = true
print("Location services are not enabled")

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)), animated: true)

My only thoughts are that I could get rid of the "stopUpdatingLocation() section and maybe then it would continuously update the region with the new center for every new location, however I am not sure if not having the stopUpdatingLocation is bad practice? Thanks for all advice!


Use userTrackningMode which causes the map view to center the map on that location and begin tracking the user’s location. If the map is zoomed out, the map view automatically zooms in on the user’s location, effectively changing the current visible region.

To use it

mapView.setUserTrackingMode(.follow, animated:true)