Reputation:
I have everything working except the actual button function code. Here is My code but it does not add an annotation.
@IBAction func AddAnnotation(_ sender: UIButton) {
CLLocationManager().startUpdatingLocation()
let annotation = MKPointAnnotation()
// Set the annotation by the lat and long variables
annotation.coordinate = CLLocationCoordinate2D()
annotation.title = "My Car"
self.map.addAnnotation(annotation)
}
Upvotes: 0
Views: 56
Reputation: 131481
Your code can't possibly work. When you call startUpdatingLocation()
, it takes several seconds for the GPS to start up and get an accurate fix. you have to set yourself up as it's delegate, and then wait for your locationManager(_:didUpdateLocations:)
method to be called.
You'd put your code to add an annotation in that method.
As others have said, you also need to write code that checks to see if you are authorized to get the user's location, and ask permission if not. (And You'll need to add a special key to your app's info.plist file indicating that your app needs access to the user's location.)
Take a look at the documentation on Core Location and using the location Manager in Xcode, and you might want to find a tutorial that walks you through the steps. It's a little involved.
Upvotes: 1