Skip to main content

Add a view annotation

This UIKit example shows you how to spawn a ViewAnnotation on a MapView when the map is clicked. A ViewAnnotation is a UI pop-up that can contain text and other data. In this example we can spawn a ViewAnnotation wherever the user clicks on screen.

Add AnnotationView class to your project

This example uses AnnotationView, a custom class defined in the Maps SDK for the iOS Examples App. To use this code snippet, you must also add the AnnotationView class to your project.

ViewAnnotationBasicExample.swift
import UIKit
import MapboxMaps
import CoreLocation

final class ViewController: UIViewController {
private var mapView: MapView!
private var cancelables = Set<AnyCancelable>()

override func viewDidLoad() {
super.viewDidLoad()

let centerCoordinate = CLLocationCoordinate2D(latitude: 39.7128, longitude: -75.0060)
let options = MapInitOptions(cameraOptions: CameraOptions(center: centerCoordinate, zoom: 7))

mapView = MapView(frame: view.bounds, mapInitOptions: options)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)

addViewAnnotation(at: mapView.mapboxMap.coordinate(for: mapView.center))

mapView.mapboxMap.onMapLoaded.observeNext { [weak self] _ in
guard let self = self else { return }

}.store(in: &cancelables)

mapView.gestures.onMapTap.observe { [weak self] context in
self?.addViewAnnotation(at: context.coordinate)
}.store(in: &cancelables)
}

private func addViewAnnotation(at coordinate: CLLocationCoordinate2D) {
let annotationView = AnnotationView(frame: CGRect(x: 0, y: 0, width: 100, height: 80))
annotationView.title = String(format: "lat=%.2f\nlon=%.2f", coordinate.latitude, coordinate.longitude)
let annotation = ViewAnnotation(coordinate: coordinate, view: annotationView)
annotation.allowOverlap = true
annotationView.onClose = { [weak annotation] in annotation?.remove() }
annotationView.onSelect = { [weak annotation] selected in
annotation?.selected = selected
annotation?.setNeedsUpdateSize()
}
mapView.viewAnnotations.add(annotation)
}
}
Was this example helpful?