Add Marker (iOS)
Place markers (annotations) on the map to highlight specific locations.
MapSession required
Remember to integrate the MapSession in your app. The MapSession must be called periodically every 10 minutes while the map is active.
Single Annotation
import UIKit
import MapLibre
class MarkerViewController: UIViewController, MLNMapViewDelegate {
private var mapView: MLNMapView!
override func viewDidLoad() {
super.viewDidLoad()
let styleURL = URL(string:
"https://tiles.smartmaps.cloud/styles/v1/smartmaps/light/style.json?apiKey=[INSERT API-KEY]&channel=app"
)!
mapView = MLNMapView(frame: view.bounds, styleURL: styleURL)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.delegate = self
mapView.setCenter(
CLLocationCoordinate2D(latitude: 49.0069, longitude: 8.4037),
zoomLevel: 12,
animated: false
)
view.addSubview(mapView)
}
func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) {
let annotation = MLNPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(
latitude: 49.0069,
longitude: 8.4037
)
annotation.title = "Karlsruhe"
annotation.subtitle = "SmartMaps Headquarters"
mapView.addAnnotation(annotation)
}
// Enable callout on tap
func mapView(_ mapView: MLNMapView, annotationCanShowCallout annotation: MLNAnnotation) -> Bool {
return true
}
}
Multiple Annotations
func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) {
let locations: [(CLLocationCoordinate2D, String, String)] = [
(CLLocationCoordinate2D(latitude: 49.0069, longitude: 8.4037), "Karlsruhe", "Baden-Wuerttemberg"),
(CLLocationCoordinate2D(latitude: 48.7758, longitude: 9.1829), "Stuttgart", "State Capital"),
(CLLocationCoordinate2D(latitude: 49.4875, longitude: 8.4660), "Mannheim", "Rhine-Neckar Region"),
(CLLocationCoordinate2D(latitude: 48.3705, longitude: 10.8978), "Augsburg", "Bavaria")
]
var annotations = [MLNPointAnnotation]()
for (coordinate, title, subtitle) in locations {
let annotation = MLNPointAnnotation()
annotation.coordinate = coordinate
annotation.title = title
annotation.subtitle = subtitle
annotations.append(annotation)
}
mapView.addAnnotations(annotations)
// Fit camera to show all annotations
mapView.showAnnotations(annotations, animated: true)
}
Custom Marker Image
func mapView(_ mapView: MLNMapView, imageFor annotation: MLNAnnotation) -> MLNAnnotationImage? {
let reuseIdentifier = "custom-marker"
if let existingImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier) {
return existingImage
}
guard let image = UIImage(named: "custom-marker") else { return nil }
return MLNAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
}