MapQuest iOS SDK

Custom User Location Annotation

Custom User Location

This can be achieved by implementing func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? and returning an instance of MGLUserLocationAnnotationView or a subclass of MGLUserLocationAnnotationView

- (nullable MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id )annotation;
{
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        
      // For better performance, always try to reuse existing annotations.

      MGLUserLocationAnnotationView *userLocationAnnotationView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:@"annotationView"];
        
      if (!userLocationAnnotationView) {
          
        //create a new annotation view
        userLocationAnnotationView = [[MGLUserLocationAnnotationView alloc] initWithReuseIdentifier:@"annotationView"];
        UIImage *userLocationAnnotationImage = [UIImage imageNamed:@"icon_spaceship.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:userLocationAnnotationImage];            

        //add image to annotation
        [userLocationAnnotationView addSubview:imageView];
        return userLocationAnnotationView;
      }
        
    }
    return nil;
}
 func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        
    if annotation is MGLUserLocation {
    
        // For better performance, always try to reuse existing annotations.
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "userAnnotation")
    
        if annotationView == nil {
            
            //create a new annotation view
            annotationView =  MGLUserLocationAnnotationView(reuseIdentifier: "userAnnotation")
            
            annotationView?.frame = CGRect(x: 0, y: 0, width: 40 , height: 40)
            
            let userLocationAnnotationImageView = UIImageView(frame: CGRect(x: 0, y: 0, width:40, height: 40))
            let userLocationAnnotationImage = UIImage(named: "icon_spaceship")
            userLocationAnnotationImageView.image = userLocationAnnotationImage
            
            //add image to annotation
            annotationView?.addSubview(userLocationAnnotationImageView)
            
            return annotationView;
        }
    }
    return nil;
}