← Back to Tutorials

11. Maps & Location

Networking & Communication

MapKit Basics

Display interactive maps with annotations:

import MapKit

// Add map view
let mapView = MKMapView(frame: view.bounds)
mapView.mapType = .standard
view.addSubview(mapView)

// Center on a location
let coordinate = CLLocationCoordinate2D(
    latitude: 37.7749, longitude: -122.4194)
let region = MKCoordinateRegion(
    center: coordinate,
    latitudinalMeters: 1000,
    longitudinalMeters: 1000)
mapView.setRegion(region, animated: true)

Annotations

Add pins and custom markers:

// Basic pin
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "San Francisco"
annotation.subtitle = "California"
mapView.addAnnotation(annotation)

// Custom annotation view
func mapView(_ mapView: MKMapView,
    viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let view = MKMarkerAnnotationView(
        annotation: annotation, reuseIdentifier: "pin")
    view.markerTintColor = .systemBlue
    view.canShowCallout = true
    return view
}

Core Location Integration

Show user location and track movement:

mapView.showsUserLocation = true
mapView.userTrackingMode = .follow

// Add overlays (route lines, polygons)
let polyline = MKPolyline(coordinates: coordinates,
    count: coordinates.count)
mapView.addOverlay(polyline)

// Overlay renderer
func mapView(_ mapView: MKMapView,
    rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.strokeColor = .systemBlue
        renderer.lineWidth = 3
        return renderer
    }
    return MKOverlayRenderer(overlay: overlay)
}

Geocoding

Convert addresses to coordinates and vice versa:

let geocoder = CLGeocoder()

// Forward geocoding
geocoder.geocodeAddressString("1 Infinite Loop, Cupertino, CA") {
    placemarks, error in
    if let placemark = placemarks?.first {
        print(placemark.location?.coordinate ?? "")
    }
}

// Reverse geocoding
let location = CLLocation(latitude: 37.7749, longitude: -122.4194)
geocoder.reverseGeocodeLocation(location) { placemarks, error in
    if let placemark = placemarks?.first {
        print(placemark.locality ?? "")
    }
}
Practice Task: Build a "Nearby Places" app that shows the user's current location on a map. Use MKLocalSearch to find nearby restaurants or cafes. Display them as custom annotation pins. Show a route from the user's location to a selected place using MKDirectionsRequest.