How to change MKMapView's user-location blue dot to an image of choice?

后端 未结 5 1530
盖世英雄少女心
盖世英雄少女心 2020-12-02 09:27

Is it possible to change the blue dot which indicates the user\'s location in MKMapView to an image? For example a little car or any .png image?

5条回答
  •  心在旅途
    2020-12-02 09:55

    Please try this something like this. its working for me in Xcode 7 and swift 2.

        func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    
        // want to show a custom image if the annotation is the user's location.
        guard !annotation.isKindOfClass(MKUserLocation) else {
            let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "userLocation")
            annotationView.image = UIImage(named: "icon_coordinates_self")
            return annotationView
            //return nil
        }
    
        // for other annotation except current location 
        let annotationIdentifier = "AnnotationIdentifier"
    
        var annotationView: MKAnnotationView?
        if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) {
            annotationView = dequeuedAnnotationView
            annotationView?.annotation = annotation
        }
        else {
            let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
            av.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
            annotationView = av
        }
    
        if let annotationView = annotationView {
            // Configure your annotation view here
            annotationView.canShowCallout = true
            annotationView.image = UIImage(named: "Annotation_map")
        }
    
        return annotationView
    }
    

提交回复
热议问题