Skip to content

Instantly share code, notes, and snippets.

@hskang9
Created May 29, 2017 11:47
Show Gist options
  • Save hskang9/72bfe1738b4a5af5f27bc284855ad893 to your computer and use it in GitHub Desktop.
Save hskang9/72bfe1738b4a5af5f27bc284855ad893 to your computer and use it in GitHub Desktop.
import CoreLocation and track user's current location using location manager
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var mapView: MKMapView!
let locationManager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01) // set scale factor
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
locationManager.stopUpdatingLocation() // This is for toggling otherwise locationManager will keep tracking in focus
}
override func loadView() {
// Create a MapView
mapView = MKMapView()
// set it as *the* view of this view controller
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment