Search code examples
swiftswiftuimapboxmapbox-ios

Use Custom Annotation Image in MapBox SwiftUI


I've recently followed the tutorial for integrating MapBox into my SwiftUI app using this tutorial by MapBox. I'm now looking to customize the image used for the annotation marker on the map. Has anybody done this or is willing to give a short example of how this can be accomplished with MapBox and SwiftUI? My current code looks nearly identical to the tutorial above.

Thank you so much for your time!


Solution

  • I ended up figuring this out, so I'll post this for other users.

    The current annotation guide doesn't offer any example on how to do this directly in SwiftUI, however, you can use some of the functions built-in to accomplish the exact task. In the Coordinator class shown in the original documentation, you can simply add the following method to show whichever image you'd like at each annotation.

    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
                
        return MGLAnnotationImage(image: UIImage(named: "imageName")!, reuseIdentifier: "map-marker")
                
    }