swiftannotationsmkannotationviewmkmapviewdelegate

MapView User's Current Location Regular Pin


Im having trouble putting a "regular" pin on the user's current location. I searched around but couldn't find much. Right now, in the user's current location I just have the location beacon. How can I change it to just the regular "pin"? I tried nnotationView?.annotation = annotation but this did not seem to work.

extension ViewController: MKMapViewDelegate {

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationView")

        if annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationView")
        }

        if let title = annotation.title, title == "Park Test" {

            annotationView?.image = UIImage(named: "Park icon test")

        } 

   else if annotation === mapView.userLocation {

            return nil
        }

        annotationView?.canShowCallout = true

        return annotationView

    }

Solution

  • My code using annotations.

      func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?  {
    
        let identifier = "MyCustomAnnotation"
    
        if annotation is MKUserLocation { return nil }
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
    
        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView?.canShowCallout = true
            annotationView?.isEnabled = true
            annotationView?.isDraggable = true
            let btn = UIButton(type: .detailDisclosure)
            annotationView?.rightCalloutAccessoryView = btn
        } else {
            annotationView?.annotation = annotation
        }
        return annotationView
    }
    

    Call the delegate by adding this code.

     var point = MKPointAnnotation()
     self.point.coordinate = location.coordinate
     self.point.title = ("Your title")
     self.point.subtitle = (" your subs")
     self.mapView.addAnnotation(self.point)
     //selects the annotation
     self.mapView.selectAnnotation(self.point, animated: true)