Reputation: 53
Mapbox provides handy documentation on customising an annotation's image and customising an annotation's view:
https://www.mapbox.com/ios-sdk/examples/annotation-views/ https://www.mapbox.com/ios-sdk/examples/marker-image/
However it doesn't seem possible to combine these ideas and customise an annotation view's image. Basically what I am hoping to do is have an annotation of a photo (which the user picks) which also has a boarder which can be animated when tapped.
Has anyone ran into this limitation as well?
Upvotes: 3
Views: 3409
Reputation: 1163
func mapView( _ mapView: MGLMapView, imageFor annotation: MGLAnnotation ) -> MGLAnnotationImage? {
var annotationImage : MGLAnnotationImage? = nil
annotationImage = MGLAnnotationImage( image:UIImage( named: "imageyouwanttoset", reuseIdentifier: annotation.title ) )
return annotationImage
}
Upvotes: 1
Reputation: 2421
MGLAnnotationView
inherits from UIView
, so most any technique you might use to add an image to a view will also work here.
A simple way would be to add UIImageView
as a subview in a custom MGLAnnotationView
subclass:
class CustomImageAnnotationView: MGLAnnotationView {
var imageView: UIImageView!
required init(reuseIdentifier: String?, image: UIImage) {
super.init(reuseIdentifier: reuseIdentifier)
self.imageView = UIImageView(image: image)
self.addSubview(self.imageView)
self.frame = self.imageView.frame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
}
And then use that subclass in mapView:viewForAnnotation:
:
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
guard annotation is MGLPointAnnotation else {
return nil
}
let imageName = "someImageThatYouHaveAddedToYourAppBundle"
// Use the image name as the reuse identifier for its view.
let reuseIdentifier = imageName
// For better performance, always try to reuse existing annotations.
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
// If there’s no reusable annotation view available, initialize a new one.
if annotationView == nil {
annotationView = CustomImageAnnotationView(reuseIdentifier: reuseIdentifier, image: UIImage(named: imageName)!)
}
return annotationView
}
Upvotes: 7