Custom annotation on the map

55 views Asked by At

I have an app where the user presses a button and takes a photo, then the photo goes to ImageAnnotation class and it must be added to the map, but I get such an error: "Unexpectedly found while implicitly unwrapping the optional"

Only this error prevents the app to work correctly, if You can help me I would appreciate that highly

So here is the code

extension MapViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    picker.dismiss(animated: true, completion: nil)
    
    guard let ecoImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
    
    guard let currentLocation = locationManager.location else { return }

    let pin = ImageAnnotation(coordinate: CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude), image: ecoImage, color: UIColor.systemGreen)
}

}

Here is the class that must create a custom annotation for the map

class ImageAnnotation : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var imageEco: UIImage?
var color: UIColor?
var imageView: UIImageView!

init(coordinate: CLLocationCoordinate2D, image: UIImage, color: UIColor) {
    self.coordinate = coordinate
    imageEco = image
    self.color = color
    imageView.image = image
    imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
    imageView.addSubview(self.imageView)

    self.imageView.layer.cornerRadius = 25
    self.imageView.layer.masksToBounds = true
}

}

Here is the final result that must be implemented

1

There are 1 answers

0
matt On

You are saying imageView.image = image. But imageView is nil. So you crash. No big surprise.

Taking a larger perspective, it appears that you have failed to appreciate the difference between an annotation and an annotation view. An annotation is just a message carrier: it can say what the coordinate is and perhaps what image should be displayed, but that's all. It is the job of your map view delegate to create the corresponding annotation view on demand, and that is where you are dealing with a view and can arrange for it to display your circular image.