メインコンテンツまでスキップ

Add a view annotation

This example demonstrates ViewAnnotation in the Mapbox Maps SDK for iOS. The example initializes a MapView and listens for map loaded event and map tap gesture using onMapLoaded and onMapTap. The example adds a custom view annotation, based on user interaction, to the map at a given coordinate and displays it with details like latitude and longitude. Interaction events such as close and selection on the annotation view are also handled within the implementation.

View annotations are added via ViewAnnotation objects, controlled by methods like remove() for closing an annotation and setNeedsUpdateSize() for adjusting the annotation's size.

Add AnnotationView class to your project

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

iOS Examples App Available

This example code is part of the Maps SDK for iOS Examples App, a working iOS project available on Github. iOS developers are encouraged to run the examples app locally to interact with this example in an emulator and explore other features of the Maps SDK.

See our Run the Maps SDK for iOS Examples App tutorial for step-by-step instructions.

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)
}
}
このexampleは役に立ちましたか?