MapKit basics for Swift developers: maps, annotations and pins
MapKit ships inside iOS, which means a map screen never needs a third-party SDK, an API key or a separate tile licence. The framework hands you two front ends — MKMapView for UIKit and the Map view for SwiftUI — plus a family of annotation classes that turn a plain coordinate into something a person can tap. The code involved is short; the decisions are not. Which annotation type to use, when to fit the region, and how to handle a location permission prompt are the choices that separate a map that feels native from one that feels like a web view in disguise.
I build Swift apps from Atyrau in Kazakhstan, and every map feature I write follows the same routine: drop in a map, register a delegate, add annotations, fit the region. Australian apps are no different in structure, and they bring their own geography with them. A café finder in Melbourne's laneways, a pickup map for the nearest Bunnings sausage sizzle, a ferry timetable around Circular Quay, a delivery radius in kilometres from Perth — each one starts with a coordinate and a span. What follows is that path in full, including the small details that keep it working on real devices.
Adding a map to an Xcode project
Create the app target as usual and import MapKit. Nothing else is required: Apple's own tiles, road labels, search results and place names come with the operating system, so there is no network configuration to write and no account to register for. In UIKit, MKMapView is an ordinary UIView subclass that you add as a subview and lay out with Auto Layout or constraints. In SwiftUI, Map is a view you drop into any container, and on iOS 17 and later it accepts a MapCameraPosition binding for full control over the camera.
import MapKit
final class HarbourMapViewController: UIViewController, MKMapViewDelegate {
private let mapView = MKMapView()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
view.addSubview(mapView)
}
}
The SwiftUI equivalent is even shorter, and Marker gives you a pin with a title in a single declaration:
import MapKit
import SwiftUI
struct LandmarksMap: View {
var body: some View {
Map {
Marker("Circular Quay",
coordinate: CLLocationCoordinate2D(latitude: -33.8709, longitude: 151.2090))
}
}
}
Both surfaces expose the same machinery underneath: a delegate that vends annotation views, a camera that can be moved with animation, and overlays for routes. Pick one and stay with it, because embedding a MKMapView inside a SwiftUI layout tends to produce gesture conflicts and duplicated scroll behaviour that are tedious to unwind later.
Turning coordinates into a map region
A coordinate is a point on the globe. A region is that point plus a span, and the span is measured in degrees rather than kilometres. One degree of latitude is roughly 111 kilometres, so a span of 0.02 covers a little over two kilometres from north to south. Set the span too tight and your pins fall outside the visible area; set it too wide and the map becomes a coloured rectangle with a pin somewhere in it.
let centre = CLLocationCoordinate2D(latitude: -33.8568, longitude: 151.2153)
let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
mapView.setRegion(MKCoordinateRegion(center: centre, span: span), animated: true)
Scale matters a lot in Australia. A neighbourhood around Bondi Junction wants a span below 0.01, a view of Sydney Harbour is comfortable around 0.05, and showing the whole country — Perth to Adelaide is close to 2,700 kilometres — needs a span in the thirties rather than single digits. Hard-coded spans break the moment your dataset grows, so prefer fitting the map to the annotations you actually have.
showAnnotations(_:animated:) does that for you, and MKMapRect plus MKMapRectThatFits handles it manually when you need padding for callouts or a bottom sheet:
mapView.showAnnotations(cafes, animated: true)
let rect = MKMapRect.null
for cafe in cafes {
let point = MKMapPoint(cafe.coordinate)
rect = rect.union(MKMapRect(x: point.x, y: point.y, width: 0, height: 0))
}
mapView.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 80, left: 40, bottom: 220, right: 40), animated: true)
Overlays sit on the same layer. A MKPolyline draws a route or a boundary, and an MKTileOverlay lets you supply your own tile images, which is how people replace Apple's map with OpenStreetMap tiles in areas with poor coverage — remember that OpenStreetMap requires visible attribution.
Choosing the right annotation type
MapKit provides several annotation classes, and the one you pick determines whether you get a coloured pin, your own artwork, a grouped bubble or the blue location dot. Each behaves differently inside the delegate, so choosing early keeps the view code predictable.
| Annotation type | What it provides | Best suited to | Common pitfall |
|---|---|---|---|
MKPointAnnotation |
A coordinate with an optional title and subtitle | Quick drops of a coordinate from an API | Gives no tint or image without a delegate |
MKMarkerAnnotation |
Coloured pin, title and optional glyph | Most app pins from iOS 11 onwards | Marker colours can clash with status colours |
Custom MKAnnotation subclass |
Your own fields plus callout content | Points of interest with ratings or hours | You must supply the view yourself |
MKUserLocation |
The blue dot for the current position | "Near me" and navigation screens | Needs permission and careful failure handling |
MKClusterAnnotation |
A bubble counting grouped pins | Dense city maps such as Melbourne's CBD | Requires a clustering identifier on each pin |
For a custom class, keep the annotation a plain data holder and let the delegate decide how it looks:
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let cafe = annotation as? CafeAnnotation else { return nil }
let view = (mapView.dequeueReusableAnnotationView(withIdentifier: "cafe")
as? MKMarkerAnnotationView)
?? MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "cafe")
view.annotation = cafe
view.canShowCallout = true
view.markerTintColor = .systemRed
view.glyphText = "\(Int(cafe.rating))"
return view
}
Setting clusteringIdentifier on that view turns individual pins into bubbles when they overlap, which is what keeps a two-hundred-pin map of inner Melbourne readable. Callouts can carry a right accessory button for directions, a detail accessory for a custom screen, and a left accessory that many Australian listings use for a phone number in the familiar +61 2 format.
Habits that keep map features reliable
The difference between a demo map and a shipped map is a short list of habits, and none of them require clever algorithms. Most of the bugs I have seen in map code come from doing work on the wrong thread, recycling views carelessly, or asking for location permission before the user understands why.
- Reuse annotation views through
dequeueReusableAnnotationViewwith a stable identifier, and never allocate a new view for every pin in a dense result set. - Keep every mutation of the map on the main actor, including region changes and annotation additions, because
MKMapViewis not thread safe. - Request location access only when a feature needs it, and explain the reason in the
NSLocationWhenInUseUsageDescriptionrather than shipping a generic string. - Fit the region to your data with edge padding instead of hard-coding a span that will break when the dataset changes.
- Provide a fallback when reverse geocoding fails, since Australian addresses mix unit and street numbers differently and many listings use a GPO Box with no street line.
- Load remote pin images asynchronously and cancel the task when the cell is recycled, or you will end up with the wrong cafe's photo on a pin.
- Test on a real device with simulated locations in Melbourne, Darwin and Perth, because a default simulator location can sit in the ocean and produce empty searches.
Search is worth wiring up properly as well. MKLocalSearch finds points of interest near a coordinate and returns map items you can convert straight into annotations, so a "coffee near me" screen for Melbourne's CBD is a single request away. In SwiftUI, MapReader and onMapCameraChange give you the visible region as the user pans, which is exactly what you need to load more results as the map moves.
Building your first annotated map
Everything above collapses into one small project. A map with three pins, a delegate, and a fitted region exercises the majority of the framework: coordinate handling, region calculation, annotation vending, reuse, callouts and clustering. Add a MKLocalSearch request for nearby cafés and a location button that fits the map to the user, and you have the skeleton behind most production map screens.
Open Xcode, create a new iOS app named HarbourMap, add a map showing three annotations around Sydney Harbour — the Opera House, the ferry wharf at Circular Quay and the Bondi surf club — and call showAnnotations(_:animated:) so the region fits all three pins when the screen first appears.