So I'm creating my annotations in a for loop as follows in the update map view function:
for item in array {
let latitude = item.latitude
let longitude = item.longitude
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let annotation = //make an annotation that uses a different image in Assets depending on a variable called "imageID"
mapView.addAnnotation(annotation)
}
I tried using reuseIdentifiers but wasn't even getting close to figuring this out. I also tried using the imageFor function and making a custom annotation class (to detect what the image passed in was and change the view accordingly) but it didn't work:
class CustomAnnotation: NSObject, MGLAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
var image: UIImage?
init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
func mapView( _ mapView: MGLMapView, imageFor annotation: MGLAnnotation ) -> MGLAnnotationImage? {
let annotationImage: MGLAnnotationImage
let annotationImageToilet = mapView.dequeueReusableAnnotationImage(withIdentifier: "custom1")
let annotationImageDefault = mapView.dequeueReusableAnnotationImage(withIdentifier: "defaultImage")
switch annotation.image { //tried to sort according to the image value of the custom class
case "custom1":
var featureAnnotation = FeatureAnnotation(coordinate: annotation.coordinate, title: "Title", subtitle: "subtitle")
featureAnnotation.image = UIImage(named: "custom1")!
annotationImage = annotationImageToilet ?? featureAnnotation //couldn't get this line working properly
default:
var featureAnnotation = FeatureAnnotation(coordinate: annotation.coordinate, title: "Title", subtitle: "subtitle")
featureAnnotation.image = UIImage(named: "defaultImage")!
annotationImage = annotationImageDefault ?? featureAnnotation //couldn't get this line working properly
}
return annotationImage
}
Essentially, I just want the image of the custom annotations to change depending on what feature.imageID is, any help much appreciated!