I am new to Xcode and mobile app. I am doing an app to find the current location. I tested it on the simulator and got this message in the console.
"Could not inset legal attribution from corner 4". What does it mean and how can I fix it?
import UIKit
import Alamofire
import AlamofireImage
import MapKit
import CoreLocation
class MapVC: UIViewController
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
let regionRadius: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
configureLocationServices()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func centerMapPressed(_ sender: Any) {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse{
centerMapOnUserLocation()
}
}
MKMapViewDelegate:
func centerMapOnUserLocation(){
guard let coordinate = locationManager.location?.coordinate else{return}
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius*2.0, regionRadius * 2.0 )
mapView.setRegion(coordinateRegion, animated: true)
}
CLLocationManagerDelegate:
func configureLocationServices(){
if authorizationStatus == .notDetermined{
locationManager.requestAlwaysAuthorization()
}else{
return}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
this issue occurs when the required information in the right form is not found. if your device i trying to get some location or some number a variable, and that a variable is required for afun.. the value is not set into a, but afun is called that this error occurs..
call your cell's coordinates in viewdidload without any other function.
Here is the simplest way to get your cell's position.
1. you should have updated privacies of the devices under infor.plist
Add following lines into your plist before closing tag
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Privacy - Location Always and When In Use Usage Description</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Privacy - Location Always Usage Description</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Privacy - Location When In Use Usage Description</string>
after that.. this is the simplest working code .. i'm happily using it with no issue..
import CoreLocation
import MapKit
class AddressVc: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var map: MKMapView!
var locationManager = CLLocationManager()
here is code to move map in center for the required location
let latDelta:Double = 0.5
let lngDelta:Double = 0.5
let latitude:Double = 37.57554038
let longitude:Double = -122.40068475
let locationcoordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let zoomSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lngDelta)
let region = MKCoordinateRegion(center: locationcoordinates, span: zoomSpan)
self.map.setRegion(region, animated: true)
in the above code.. if you put device's lat and lng postions in latitude and lognitude that will move the map to your's devices's location.
now how to get device's location.
here is the code you can put into your viewDidLoad() function.
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// device latitude = (locationManager.location?.coordinate.latitude)!
// device longitude = (locationManager.location?.coordinate.longitude)!
}
this is detect the device's latitude and longitude values. you can put them in above mentioned code..
Here is the full code.
import CoreLocation
import MapKit
class AddressVc: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
devicelatitude = (locationManager.location?.coordinate.latitude)!
devicelongitude = (locationManager.location?.coordinate.longitude)!
let latDelta:Double = 0.5
let lngDelta:Double = 0.5
let latitude:Double = devicelatitude
let longitude:Double = devicelongitude
let locationcoordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let zoomSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lngDelta)
let region = MKCoordinateRegion(center: locationcoordinates, span: zoomSpan)
self.map.setRegion(region, animated: true)
}
I hope this will help you.. if not.. there would be many other who are facing this issue.
==========================
With the simulator open, go to the DEBUG menu on the mac top bar, the last option is location, mine was showing this error when set to NONE. Set it Custom Location, first with you prompt you to a custom location on a new window, fill that, close the simulator, and relaunch the app. It should get the custom location from your code now. (andrecasarini credit)
This error occurs when the "Legal" link on the bottom left of the MapView is not within bounds or is obscured. There are similar errors for the map's scale and for the compass that appears when rotating.
Consider using size constraints or a safeAreaInset.
I believe the legal inset bug is in Apple's mapkit initialization code and unrelated to what we do when we use the code. Here's my reasoning.
If you use storyboards and the UIMapKit drag and drop module, the legal inset error pops up somewhere between the call to the initial call to application in the app delegate and the first viewDidLoad call, i.e., it's an OS error.
I got curious if I could work around it and wrote a version that doesn't use the storyboard editor. I was thinking that perhaps the editor was inserting some broken code into the app. My test app has two views, the start view and a second view with the map on it. The code is shown below. Don't be harsh, it's my first attempt at understanding what's going on with controllers views and subviews using programmatic views and subviews. It isn't pretty but it works to isolate the legal inset bug.
I started by building a new xcode project and deleting the storyboard. I then replaced the application function stub in appdelegate with the following code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let viewController = ViewController()
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
let mapView = mapViewController()
mapView.otherView = viewController
viewController.mapView = mapView
return true
}
Even though the mapView is created here, the legal inset error doesn't show up. What does show up are a couple of other messages about scale and compass having some sort of issue. Since I was focusing on the legal inset bug, I ignored them and moved on.
I then replaced the default view controller with code that created two subviews, one a subview that serves as a button to switch to the second view controller and the second subview that serves as "you're on the first view" marker view. That required figuring out how to handle a tap. The color changing code in the tap handler was initial "hello world. I see a tap" code and serves no other purpose.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
let DynamicView = UIView()
let switchView = UIView(frame: CGRect(x: UIScreen.main.bounds.minX+10, y: UIScreen.main.bounds.minY+20, width: 40, height: 40))
public var mapView:mapViewController? = nil
public var otherView:UIViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = .white
DynamicView.backgroundColor = .yellow
DynamicView.layer.cornerRadius = 25
DynamicView.layer.borderWidth = 2
switchView.backgroundColor = .orange
switchView.layer.borderWidth = 2
var gR = UITapGestureRecognizer(target: self, action:#selector(self.handlebigTap(_:)))
DynamicView.addGestureRecognizer(gR)
gR = UITapGestureRecognizer(target: self, action:#selector(self.handlesmallTap(_:)))
switchView.addGestureRecognizer(gR)
self.view.addSubview(switchView)
self.view.addSubview(DynamicView)
DynamicView.translatesAutoresizingMaskIntoConstraints = false
let margins = view.layoutMarginsGuide
DynamicView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 10).isActive = true
DynamicView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 10).isActive = true
DynamicView.topAnchor.constraint(equalTo: margins.topAnchor, constant: 40).isActive = true
DynamicView.bottomAnchor.constraint(equalTo: margins.topAnchor, constant: 110).isActive = true
}
#objc func handlebigTap(_ sender: UITapGestureRecognizer) {
if ( self.DynamicView.backgroundColor == .green){
self.DynamicView.backgroundColor = .blue
} else {
self.DynamicView.backgroundColor = .green
}
}
#objc func handlesmallTap(_ sender: UITapGestureRecognizer) {
if ( self.switchView.backgroundColor == .orange){
self.switchView.backgroundColor = .blue
present(mapView!, animated: true, completion: nil)
} else {
self.switchView.backgroundColor = .orange
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
At this point, I checked to see if the first call to viewDidLoad triggered the legal inset error and saw that it did not. That meant the error was being triggered somewhere in the mapKit initialization code which was yet to be built. I simply copied and pasted the first viewController into a new file and called that mapViewController. I commented out the DynamicView code left over from the first controller and added the mapKit initialization code as shown here:
import UIKit
import MapKit
import CoreLocation
class mapViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
let DynamicView = UIView(frame: CGRect(x: UIScreen.main.bounds.maxX-110, y: UIScreen.main.bounds.maxY-110, width: 100, height: 100))
let switchView = UIView(frame: CGRect(x: UIScreen.main.bounds.minX+10, y: UIScreen.main.bounds.minY+20, width: 40, height: 40))
var mapView = MKMapView()
public var otherView:UIViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = .white
// DynamicView.backgroundColor = .yellow
// DynamicView.layer.cornerRadius = 25
// DynamicView.layer.borderWidth = 2
switchView.backgroundColor = .orange
switchView.layer.borderWidth = 2
var gR = UITapGestureRecognizer(target: self, action:#selector(self.handlebigTap(_:)))
DynamicView.addGestureRecognizer(gR)
gR = UITapGestureRecognizer(target: self, action:#selector(self.handlesmallTap(_:)))
switchView.addGestureRecognizer(gR)
self.view.addSubview(switchView)
// self.view.addSubview(DynamicView)
// mapView.frame = CGRect(x: 10, y: 60, width: view.frame.size.width-20, height: 300)
mapView.mapType = MKMapType.standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
view.addSubview(mapView)
mapView.translatesAutoresizingMaskIntoConstraints = false
let margins = view.layoutMarginsGuide
mapView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 10).isActive = true
mapView.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 0).isActive = true
mapView.topAnchor.constraint(equalTo: margins.topAnchor, constant: 45).isActive = true
mapView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -20).isActive = true
}
#objc func handlebigTap(_ sender: UITapGestureRecognizer) {
if ( self.DynamicView.backgroundColor == .green){
self.DynamicView.backgroundColor = .blue
} else {
self.DynamicView.backgroundColor = .green
}
}
#objc func handlesmallTap(_ sender: UITapGestureRecognizer) {
if ( self.switchView.backgroundColor == .orange){
self.switchView.backgroundColor = .blue
dismiss(animated: true, completion: nil)
} else {
self.switchView.backgroundColor = .orange
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
}
I ran the above code and stepped through looking for the legal inset message to show up. This is the offending line:
mapView.frame = CGRect(x: 10, y: 60, width: view.frame.size.width-20, height: 300)
As soon as the view is framed, the error message comes out. Doesn't matter what dimensions you give the view, the message appears. OK.... Maybe the message expects a constraint based framing instead of hard coded per the offending line.
I commented out the line and added constraints to the view and still the error popped up.
At this point I gave up. I couldn't figure out how to configure a map view so the error message doesn't show up. Hopefully Apple will pipe up and say something at this point or someone else will pick up the baton to see if there's a way to configure mapkit to stop spewing error messages.
As for myself at least I learned how to dynamically add views, subviews, gesture recognizers and constraints so my time was profitably spent chasing the bug. Thanks to all who posted sample dynamic view code, gesture recognition code, subview code and constraint code. You may recognize a bit of your code here.
You have not typed in an opening curly bracket for your MapVC Class:
your code:
class MapVC: UIViewController
to fix:
class MapVC: UIViewController {
I want to use double click. I have written function doubleTap. How to recognize location of finger?
override func viewDidLoad()
{
super.viewDidLoad()
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap")
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
view.addGestureRecognizer(doubleTap)
}
func doubleTap()
{
}
You can use location(ofTouch:in:) to get the location of the touch. However, you need access to the gesture recognizer from inside the function where you want to access the location, so you should declare doubleTap as an instance property of your class.
class YourViewController: UIViewController {
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(YourViewController.doubleTap))
override func viewDidLoad(){
super.viewDidLoad()
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
view.addGestureRecognizer(doubleTap)
}
func doubleTap(){
let touchLocation = doubleTap.location(ofTouch: numberOfTouches-1,in: nil)
}
}
Change the input parameters to the function if you want to change whether you need to get the first or last touch's location or if you want to get the location relative to a subview.
You can get the gesture recognizer as a parameter
override func viewDidLoad()
{
super.viewDidLoad()
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapFunc))
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
view.addGestureRecognizer(doubleTap)
}
func doubleTapFunc(_ sender: UITapGestureRecognizer)
{
// Use 'sender' here to get the location
if sender.state == .ended {
// handling code
let location = sender.location(ofTouch: 0, in: self.view!)
}
}
I have a issue with my swipe gesture on a MapView, to be more accurate I have issues with the first swipe gesture on a MapView because it does not does a function & moves the screen at the same time.
The code recognize my location, put an annotation on me, and runs a 5 sec timer that allows the app to add new annotations only every 5 secs. The MapView follows my path as usually. All good so far. Check the pic of my simulator at the end.
Then it occurred to me that it would be a good idea to allow the user to scape from that region and explore the rest of the map. The user can do that only swiping in any direction. And when the user is at any other location he can press the "getBack" button to center the map on his current location. All works good too.
The issue is that when the gesture Swipe is detected , that first swipe does not move the screen. It is only the second swift which does it.
I think that may be the first swipe only stops the map from following my path, and then the second one is the one that moves the screen.
Is there a way for the first swipe to stop following my path and move the map at the same time ?
I hope I made myself clear :(
The Code of the ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
let latDelta:CLLocationDegrees = 0.05
let longDelta:CLLocationDegrees = 0.05
var reStartCountClock = true
var getBackInPlace = true
var timer = NSTimer()
#IBAction func getBack(sender: AnyObject) {
getBackInPlace = true
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let uilpgr = UILongPressGestureRecognizer(target: self, action: "actionWhenPressed:")
uilpgr.minimumPressDuration = 1
map.addGestureRecognizer(uilpgr)
let uilpgrD = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrD.direction = .Down
let uilpgrU = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrU.direction = .Up
let uilpgrR = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrR.direction = .Right
let uilpgrL = UISwipeGestureRecognizer(target: self, action:Selector("handleSwipe:"))
uilpgrL.direction = .Left
map.addGestureRecognizer(uilpgrD)
map.addGestureRecognizer(uilpgrR)
map.addGestureRecognizer(uilpgrL)
map.addGestureRecognizer(uilpgrU)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locationOnline:CLLocation = locations[0]
let spanOnline:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let centerOnline:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationOnline.coordinate.latitude, locationOnline.coordinate.longitude)
let regionOnline:MKCoordinateRegion = MKCoordinateRegionMake(centerOnline, spanOnline)
if getBackInPlace == true {
self.map.setRegion(regionOnline, animated: true)
}
if reStartCountClock == true {
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "Anota", userInfo: nil, repeats: true)
reStartCountClock = false
let annotationOnline = MKPointAnnotation()
annotationOnline.title = "Updated Location"
annotationOnline.subtitle = "Pin Pam Pum"
annotationOnline.coordinate = centerOnline
self.map.addAnnotation(annotationOnline)
}
}
func handleSwipe (gestureRecognizer: UIGestureRecognizer)
{
getBackInPlace = false
print("Entra en el gesto")
}
func Anota (){
reStartCountClock = true
timer.invalidate()
}
func actionWhenPressed (gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began
{
getBackInPlace = false
print("Gesture Recognized")
let touch = gestureRecognizer.locationInView(self.map)
let touchCoordinate:CLLocationCoordinate2D = map.convertPoint(touch, toCoordinateFromView: self.map)
let touchAnnotation = MKPointAnnotation()
touchAnnotation.coordinate = touchCoordinate
touchAnnotation.title = "You tapped here"
touchAnnotation.subtitle = "It is a recommended place"
self.map.addAnnotation(touchAnnotation)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The Simulator:
I have the following code and no error when I run this. long press is working fine and double tap is not working. I have disabled the zoom before adding the double tap gesture.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
routeMapView.zoomEnabled = false
routeMapView.showsPointsOfInterest = true
let doubleTapGesture = UITapGestureRecognizer(target: self, action: "routeMapDoubleTapSelector:")
doubleTapGesture.numberOfTapsRequired = 2
routeMapView.addGestureRecognizer(doubleTapGesture)
let ulpgr = UILongPressGestureRecognizer(target: self, action:"routeMapLongPressSelector:")
ulpgr.minimumPressDuration = 2.0
routeMapView.addGestureRecognizer(ulpgr)
}
Any help?
I tried your code and it seem to be working fine. "double taps" is printed. Here's the test code.
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
let routeMapView = MKMapView()
self.view = routeMapView
routeMapView.zoomEnabled = false
routeMapView.showsPointsOfInterest = true
let doubleTapGesture = UITapGestureRecognizer(target: self, action: "routeMapDoubleTapSelector:")
doubleTapGesture.numberOfTapsRequired = 2
routeMapView.addGestureRecognizer(doubleTapGesture)
let ulpgr = UILongPressGestureRecognizer(target: self, action:"routeMapLongPressSelector:")
ulpgr.minimumPressDuration = 2.0
routeMapView.addGestureRecognizer(ulpgr)
}
func routeMapDoubleTapSelector(sender: AnyObject) {
NSLog("double taps")
}
func routeMapLongPressSelector(sender: AnyObject) {
NSLog("long press")
}
}
I want to display user location and the surrounding area, but I also want to allow the user to pan around the area. Right now if I try to scroll somewhere else on the map it automatically takes me back to the base region with the user at the center. How do I stop this? I want to show the initial view with the user in the center, but I want to be able to scroll around too. Thanks in advance you guys are so helpful!
import UIKit
import MapKit
import CoreLocation
class ViewControllerMain: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
mapView.delegate = self
let longPress = UILongPressGestureRecognizer(target: self, action: "action:")
longPress.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPress)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let regionToZoom = MKCoordinateRegionMake(manager.location.coordinate, MKCoordinateSpanMake(0.01, 0.01))
mapView.setRegion(regionToZoom, animated: true)
}
Your code in didUpdateLocations is resetting the region. You have two options.
Store in an ivar whether or not you have already set the first location. Only if you haven't do you then set the region.
Set a timer that runs for 15 seconds. If the map is moved by the user you reset the timer. When the timer expires you can recenter to the users location.
This will keep the map centred around the user but will enable them to pan around a bit to get some context.
This answer shows how to do it in Objective-C
locationManager.stopUpdatingLocation();
this is all you need at end of locationManager fun, if you are still looking for
This thread had a good example in both Swift and Obj C. Be sure to look for the comment on the answer I've linked to if you use Swift.
After you set that up, use Control Flow within the didUpdateLocations, so that it re-centers the user's location only if the user has not touched the map.
Here is my full code as an example:
#IBOutlet weak var theMap: MKMapView!
// ...
// This var and the three following functions are used to tell if the map moves because of the user.
// This is used in the control flow in didUpdateLocations
private var mapChangedFromUserInteraction = false
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view: UIView = self.theMap.subviews[0] as UIView
// Look through gesture recognizers to determine whether this region change is from user interaction
if let gestureRecognizers = view.gestureRecognizers {
for recognizer in gestureRecognizers {
if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
return true
}
}
}
return false
}
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
// user changed map region
println("user changed map region")
}
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
// user changed map region
println("user changed map region")
}
}
// This function is called each time the user moves.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
// Use Control Flow: if the user has moved the map, then don't re-center.
// NOTE: this is using 'mapChangedFromUserInteraction' from above.
if mapChangedFromUserInteraction == true {
// do nothing, because the user has moved the map.
}
else {
// update on location to re-center on the user.
// set X and Y distances for the span (zoom). This is very zoomed in.
let spanX = 0.0005
let spanY = 0.0005
// Create a region using the user's location, and the zoo.
var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
// set the map to the new region
theMap.setRegion(newRegion, animated: true)
}
}