Created
September 8, 2022 22:07
-
-
Save johnnewman/84f86a23a33cab864570fa542632930b to your computer and use it in GitHub Desktop.
Automatically refreshing view-based annotation coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import MapboxMaps | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let mapView = MapView(frame: view.bounds) | |
mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth] | |
view.addSubview(mapView) | |
mapView.mapboxMap.onNext(.mapLoaded) { event in | |
let annotationView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: 35)) | |
annotationView.backgroundColor = .red | |
try! mapView.viewAnnotations.add(annotationView, options: self.annotationOptions) | |
self.refresh(annotation: annotationView, in: mapView) | |
} | |
} | |
var annotationOptions: ViewAnnotationOptions { | |
// For demo purposes, we use a hardcoded coordinate. | |
ViewAnnotationOptions( | |
geometry: Geometry.point(Point(.init(latitude:39.50, longitude:-98.35))), | |
allowOverlap: true, | |
anchor: .center, | |
selected: true | |
) | |
} | |
func refresh(annotation: UIView, in mapView: MapView) { | |
try! mapView.viewAnnotations.update(annotation, options: annotationOptions) | |
// Continuously update the coordinates for demo purposes. This simulates | |
// updates from an API response or from user location updates. | |
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { | |
self.refresh(annotation: annotation, in: mapView) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment