Adding Pins to Map using MapKit - Swift 3.0

roguephillips picture roguephillips · Oct 30, 2016 · Viewed 44.4k times · Source

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

Answer

Mislav Javor picture Mislav Javor · Oct 30, 2016

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