简体   繁体   中英

How to Add an annotation At your current location using CoreLocation

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)
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM