How to use custom icons with mapKit framework?

丶灬走出姿态 提交于 2019-11-29 04:21:35
Nandha

You can change the annotation image by using following code,

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
    if ([[annotation title] isEqualToString:@"Current Location"]) {    
        return nil;
    }

    MKAnnotationView *annView = [[MKAnnotationView alloc ] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    if ([[annotation title] isEqualToString:@"McDonald's"])
         annView.image = [ UIImage imageNamed:@"mcdonalds.png" ];
    else if ([[annotation title] isEqualToString:@"Apple store"])
         annView.image = [ UIImage imageNamed:@"applestore.png" ];
    else
         annView.image = [ UIImage imageNamed:@"marker.png" ];
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];   
    [infoButton addTarget:self action:@selector(showDetailsView) 
             forControlEvents:UIControlEventTouchUpInside];
    annView.rightCalloutAccessoryView = infoButton;
    annView.canShowCallout = YES;
    return annView;
}

where "marker.png" is your image file.

Swift 4 and 5:

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        // Check for type here, not for the Title!!!
        guard !(annotation is MKUserLocation) else {
            // we do not want to return a custom View for the User Location
            return nil
        }
        let identifier = "Identifier for this annotation"
        let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView.image = UIImage(named: "MyMapIcon")
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.canShowCallout = false
        return annotationView
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!