27

New coder, trying to figure out how to use MapKit. The goal is to create a map that users can add pins to using their address. However, the step I am at now, I am having trouble figuring out how to add pins to the map at all.

How can I add a pin to the map? I have been struggling to figure out how to use annotations thus far.

That's what I'm hoping for help/direction with. Thanks!

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate

{
    @IBOutlet weak var bigMap: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.bigMap.showsUserLocation = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02))

        self.bigMap.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Errors " + error.localizedDescription)
    }
}
Colin Barrett
  • 4,431
  • 1
  • 24
  • 32
roguephillips
  • 271
  • 1
  • 3
  • 4

2 Answers2

71

They're called annotations in the MapKit and you instantiate them like so:

let annotation = MKPointAnnotation()

then in the viewDidLoad() method just set the coordinates and add them to the map like:

annotation.coordinate = CLLocationCoordinate2D(latitude: 11.12, longitude: 12.11)
mapView.addAnnotation(annotation)

The numbers are your coordinates

Mislav Javor
  • 1,329
  • 1
  • 14
  • 21
18

The way that I learned how to do this is:

  1. In the same function as viewDidLoad(), place the following lines of code:

     let annotation = MKPointAnnotation()
     annotation.title = "Your text here"
     //You can also add a subtitle that displays under the annotation such as
     annotation.subtitle = "One day I'll go here..."
     annotation.coordinate = center 
    

This is the only place I can see where you have a coordinate if all else fails, just add the coordinate (search on Google if you
need to know how to create a coordinate) and set it equal to the
"annotation.coordinate" variable

map.addAnnotation(annotation)
  1. Dassit!
Hiền Đỗ
  • 450
  • 5
  • 13
danner.tech
  • 107
  • 1
  • 12