How To Place an MKPointAnnotation on a Map in Xcode
In this Tutorial you will learn How To Place a MKPointAnnotation on a Map in Xcode.
Start by creating a new Xcode Project, select “Single View App” and name it whatever you like. Add a Map Object to your view controller and then create an IBOutlet to your swift file.
Jump into the swift file and import the Map Kit framework and the errors will disappear. We are going to configure the Map view so you need to set the span, the location and also the region.
let span : MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.01,longitudeDelta: 0.01) let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(53.465865, -2.347478) let region: MKCoordinateRegion = MKCoordinateRegion(center: location,span: span) map.setRegion(region, animated: false)
The span defines the current zoom level of your map and the location is the Longitude and Latitude of the location where you want the annotation to appear. The region is set to the location and the span, so you just have to set the region on the map with your location and your map should be set up.
To Place an Annotation on the Map we just need to add the following in our viewDidLoad function.
let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Trafford Center" annotation.subtitle = "Manchester" map.addAnnotation(annotation)
Create a constant which is equal to a MKPointAnnotation, you want to set the location of the annotation to your custom location. You can set the title and subtitle by using “.title” & “.subtitle” after the name of your constant, finally we just need to add the annotation to the map by using map.addAnnotation and then the name of the annotation.
Source Code: https://github.com/GurdevSingh94/MapViewAnnotation