I'm new to the swift language, and haven't done an application with mapkit yet. But I have the map and regions set, but I'm hung up on how to allow users to add pins.
Let me clarify, I have no idea of even where to start, All I have at the moment (for the pins) is my variable, but I'm not even sure if that's correct. Any help would be much appreciated!!
What I have...
var MyPins: MKPinAnnotatoinView!
......
override func viewDidLoad() {
super.viewDidLoad()
Mapview code
.....
.....
}
Your pin variable is correct. Now you just need to add this annotation to MKMapView
.
You can also create a custom class for MKAnnotation
to add custom annotation to map view.
A beta demo for MapExampleiOS8 => Which supports Swift 2.1
Follow steps below:
1. Add MapKit.framework
to project.
2. Create Storyboard variable IBOutlet
of map view control or create it in view controller. Set delegate for this variable to override it's delegate methods:
Add delegate signature to view controller interface:
class ViewController: UIViewController, MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Set map view delegate with controller
self.mapView.delegate = self
}
}
3. Override its delegate methods:
Here we need to override mapView(_:viewForAnnotation:)
method to show annotation pins on map.
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
if (annotation.isKind(of: CustomAnnotation.self)) {
let customAnnotation = annotation as? CustomAnnotation
mapView.translatesAutoresizingMaskIntoConstraints = false
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomAnnotation") as MKAnnotationView!
if (annotationView == nil) {
annotationView = customAnnotation?.annotationView()
} else {
annotationView?.annotation = annotation;
}
self.addBounceAnimationToView(annotationView)
return annotationView
} else {
return nil
}
}
4. Add MKPointAnnotation
to map view.
You can add pin to location in map view. For simplicity add code to viewDidLoad()
method.
override func viewDidLoad() {
super.viewDidLoad()
// Set map view delegate with controller
self.mapView.delegate = self
let newYorkLocation = CLLocationCoordinate2DMake(40.730872, -74.003066)
// Drop a pin
let dropPin = MKPointAnnotation()
dropPin.coordinate = newYorkLocation
dropPin.title = "New York City"
mapView.addAnnotation(dropPin)
}
You will need to call a method for when and where the user needs to add the pin. If you want it to add a pin where the user taps and holds on the map, you will need to call a gestureRecognizer, but if you want to do it via a button you will obviously just call that in an action. Either way the documentation for adding pins is throughly discussed Here