Skip to content

Instantly share code, notes, and snippets.

@hskang9
Created May 29, 2017 11:56
Show Gist options
  • Save hskang9/fa847092478b528c1baa3ba81c0470c2 to your computer and use it in GitHub Desktop.
Save hskang9/fa847092478b528c1baa3ba81c0470c2 to your computer and use it in GitHub Desktop.
Make button programmatically and add programmatic control with event
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
// Button for current Location
let currentLocation = UIButton(frame: CGRect(x:10, y: 200, width: 50, height: 30))
currentLocation.backgroundColor = UIColor.blue
view.addSubview(currentLocation)
currentLocation.addTarget(self, action: #selector(self.getLocation(_:)), for: .touchUpInside)
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
func getLocation(_ sender: UIButton) {
locationManager.startUpdatingLocation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment