简体   繁体   中英

How do I display an annotation using the Users current location when a button is clicked?

So I am creating an app that when a button is clicked, the users current location is used to create an annotation on Apples mapkit. I have everything working except for linking the button up to code that will create the annotation and display the annotation on the map. Bellow is the code I have so far:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager = CLLocationManager()

@IBOutlet var Map: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {

    println("Updating Location \(newLocation.coordinate.latitude) , \(newLocation.coordinate.longitude) ")

    let span = MKCoordinateSpanMake(0.0009, 0.0009)
    let region = MKCoordinateRegion(center: newLocation.coordinate, span: span)
    Map.setRegion(region, animated: false)
    }
}

As you will see, I have it so it constantly shows the user where they are. I want this but I also want the user to be able to create the annotation.

My question is what code do I need to create the annotations and where does it go? I am fairly new to programing so I'm not completely comprehensive of all of the code lingo so if you would (dumb things down for me please). Also, when the user clicks the button that adds the annotation, the last annotation needs to be deleted. How would I do this? I am using Swift in Xcode.

You're almost there!

  • First, create an annotation at the top of the code (just within the class):

    var annotation = MKPointAnnotation()

  • Then, use newLocation.coordinate.latitude and .longitude to create a CLLocationCoordinate2D and set that to annotation.coordinate .

    • Then use map.title = "something" and map.addAnnotation(annotation) .

    • You'll need to have some of the variables more global to achieve this, but before you place the annotation, simply use map.removeAnnotation(annotation) - so you only ever have one annotation on the screen at a time.

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