Maps

MGLSettings


                                @interface MGLSettings : NSObject

The MGLSettings object provides a global way to set SDK properties such as apiKey, backend URL, etc.

Tile Server Configuration

Authorizing Access

  • apiKey

    The API Key used by all instances of MGLMapView in the current application. Setting this property to a value of nil has no effect.

    Note

    You must set the API key before attempting to load any style which requires the token. Therefore, you should generally set it before creating an instance of MGLMapView. The recommended way to set an api key is to add an entry to your application’s Info.plist file with the key MGLApiKey and the type String. Alternatively, you may call this method from your application delegate’s -applicationDidFinishLaunching: method.

    Declaration

    Objective-C

    @property (class, copy, nullable) NSString *apiKey;

    Swift

    class var apiKey: String? { get set }
  • Instructs the SDk to use the give tile server

    Declaration

    Objective-C

    + (void)useWellKnownTileServer:(MGLWellKnownTileServer)tileServer;

    Swift

    class func use(_ tileServer: MGLWellKnownTileServer)

MGLMapCamera


                                        @interface MGLMapCamera : NSObject <NSSecureCoding, NSCopying>

An MGLMapCamera object represents a viewpoint from which the user observes some point on an MGLMapView.

#### Related examples See the Camera animation example to learn how to create a camera that rotates around a central point. See the Restrict map panning to an area example to learn how to restrict map panning using MGLMapViewDelegate‘s -mapView:shouldChangeFromCamera:toCamera: method.

  • centerCoordinate

    Coordinate at the center of the map view.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationCoordinate2D centerCoordinate;

    Swift

    var centerCoordinate: CLLocationCoordinate2D { get set }
  • heading

    Heading measured in degrees clockwise from true north.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationDirection heading;

    Swift

    var heading: CLLocationDirection { get set }
  • pitch

    Pitch toward the horizon measured in degrees, with 0 degrees resulting in a two-dimensional map.

    Declaration

    Objective-C

    @property (nonatomic) CGFloat pitch;

    Swift

    var pitch: CGFloat { get set }
  • altitude

    The altitude (measured in meters) above the map at which the camera is situated.

    The altitude is the distance from the viewpoint to the map, perpendicular to the map plane. This property does not account for physical elevation.

    This property’s value may be less than that of the viewingDistance property. Setting this property automatically updates the viewingDistance property based on the pitch property’s current value.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationDistance altitude;

    Swift

    var altitude: CLLocationDistance { get set }
  • viewingDistance

    The straight-line distance from the viewpoint to the centerCoordinate.

    Setting this property automatically updates the altitude property based on the pitch property’s current value.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationDistance viewingDistance;

    Swift

    var viewingDistance: CLLocationDistance { get set }
  • camera

    Returns a new camera with all properties set to 0.

    Declaration

    Objective-C

    + (nonnull instancetype)camera;
  • cameraLookingAtCenterCoordinate:fromEyeCoordinate:eyeAltitude:

    Returns a new camera based on information about the camera’s viewpoint and focus point.

    Declaration

    Objective-C

    + (nonnull instancetype)
                                                cameraLookingAtCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                              fromEyeCoordinate:(CLLocationCoordinate2D)eyeCoordinate
                                                                    eyeAltitude:(CLLocationDistance)eyeAltitude;

    Swift

    convenience init(lookingAtCenter centerCoordinate: CLLocationCoordinate2D, fromEyeCoordinate eyeCoordinate: CLLocationCoordinate2D, eyeAltitude: CLLocationDistance)

    Parameters

    centerCoordinate

    The geographic coordinate on which the map should be centered.

    eyeCoordinate

    The geometric coordinate at which the camera should be situated.

    eyeAltitude

    The altitude (measured in meters) above the map at which the camera should be situated. The altitude may be less than the distance from the camera’s viewpoint to the camera’s focus point.

  • cameraLookingAtCenterCoordinate:acrossDistance:pitch:heading:

    Returns a new camera with the given distance, pitch, and heading.

    This method interprets the distance as a straight-line distance from the viewpoint to the center coordinate. To specify the altitude of the viewpoint, use the -cameraLookingAtCenterCoordinate:altitude:pitch:heading: method.

    Declaration

    Objective-C

    + (nonnull instancetype)
                                                cameraLookingAtCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                acrossDistance:(CLLocationDistance)distance
                                                        pitch:(CGFloat)pitch
                                                      heading:(CLLocationDirection)heading;

    Swift

    convenience init(lookingAtCenter centerCoordinate: CLLocationCoordinate2D, acrossDistance distance: CLLocationDistance, pitch: CGFloat, heading: CLLocationDirection)

    Parameters

    centerCoordinate

    The geographic coordinate on which the map should be centered.

    distance

    The straight-line distance from the viewpoint to the centerCoordinate.

    pitch

    The viewing angle of the camera, measured in degrees. A value of 0 results in a camera pointed straight down at the map. Angles greater than 0 result in a camera angled toward the horizon.

    heading

    The camera’s heading, measured in degrees clockwise from true north. A value of 0 means that the top edge of the map view corresponds to true north. The value 90 means the top of the map is pointing due east. The value 180 means the top of the map points due south, and so on.

  • cameraLookingAtCenterCoordinate:altitude:pitch:heading

    Returns a new camera with the given altitude, pitch, and heading.

    Declaration

    Objective-C

    + (nonnull instancetype)
                                                cameraLookingAtCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                                       altitude:(CLLocationDistance)altitude
                                                                          pitch:(CGFloat)pitch
                                                                        heading:(CLLocationDirection)heading;

    Swift

    convenience init(lookingAtCenter centerCoordinate: CLLocationCoordinate2D, altitude: CLLocationDistance, pitch: CGFloat, heading: CLLocationDirection)

    Parameters

    centerCoordinate

    The geographic coordinate on which the map should be centered.

    altitude

    The altitude (measured in meters) above the map at which the camera should be situated. The altitude may be less than the distance from the camera’s viewpoint to the camera’s focus point.

    pitch

    The viewing angle of the camera, measured in degrees. A value of 0 results in a camera pointed straight down at the map. Angles greater than 0 result in a camera angled toward the horizon.

    heading

    The camera’s heading, measured in degrees clockwise from true north. A value of 0 means that the top edge of the map view corresponds to true north. The value 90 means the top of the map is pointing due east. The value 180 means the top of the map points due south, and so on.

  • cameraLookingAtCenterCoordinate:fromDistance:pitch:heading

    Deprecated

    Use -cameraLookingAtCenterCoordinate:acrossDistance:pitch:heading: or -cameraLookingAtCenterCoordinate:altitude:pitch:heading:.

    Note

    This initializer incorrectly interprets the distance parameter. To specify the straight-line distance from the viewpoint to centerCoordinate, use the -cameraLookingAtCenterCoordinate:acrossDistance:pitch:heading: method. To specify the altitude of the viewpoint, use the -cameraLookingAtCenterCoordinate:altitude:pitch:heading: method, which has the same behavior as this initializer.

    Declaration

    Objective-C

    + (nonnull instancetype)
                                                cameraLookingAtCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                fromDistance:(CLLocationDistance)distance
                                                      pitch:(CGFloat)pitch
                                                    heading:(CLLocationDirection)heading;

    Swift

    convenience init(lookingAtCenter centerCoordinate: CLLocationCoordinate2D, fromDistance distance: CLLocationDistance, pitch: CGFloat, heading: CLLocationDirection)
  • isEqualToMapCamera:

    Returns a Boolean value indicating whether the given camera is functionally equivalent to the receiver.

    Unlike -isEqual:, this method returns YES if the difference between the coordinates, altitudes, pitches, or headings of the two camera objects is negligible.

    Declaration

    Objective-C

    - (BOOL)isEqualToMapCamera:(nonnull MGLMapCamera *)otherCamera;

    Swift

    func isEqual(to otherCamera: MGLMapCamera) -> Bool

    Parameters

    otherCamera

    The camera with which to compare the receiver.

    Return Value

    A Boolean value indicating whether the two cameras are functionally equivalent.

MGLMapView


                                @interface MGLMapView : UIView <MGLStylable>

An interactive, customizable map view with an interface similar to the one provided by Apple’s MapKit.

Using MGLMapView, you can embed the map inside a view, allow users to manipulate it with standard gestures, animate the map between different viewpoints, and present information in the form of annotations and overlays.

The map view loads scalable vector tiles that conform to the Mapbox Vector Tile Specification. It styles them with a style that conforms to the Mapbox Style Specification. Such styles can be designed in Mapbox Studio and hosted on mapbox.com.

A collection of Mapbox-hosted styles is available through the MGLStyle class. These basic styles use Mapbox Streets or Mapbox Satellite data sources, but you can specify a custom style that makes use of your own data.

Mapbox-hosted vector tiles and styles require an API access token, which you can obtain from the Mapbox account page. Access tokens associate requests to Mapbox’s vector tile and style APIs with your Mapbox account. They also deter other developers from using your styles without your permission.

Because MGLMapView loads asynchronously, several delegate methods are available for receiving map-related updates. These methods can be used to ensure that certain operations have completed before taking any additional actions. Information on these methods is located in the MGLMapViewDelegate protocol documentation.

Adding your own gesture recognizer to MGLMapView will block the corresponding gesture recognizer built into MGLMapView. To avoid conflicts, define which gesture takes precedence. For example, you can create your own UITapGestureRecognizer that will be invoked only if the default MGLMapView tap gesture fails:

let mapTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(myCustomFunction))
                                for recognizer in mapView.gestureRecognizers! where recognizer is UITapGestureRecognizer {
                                    mapTapGestureRecognizer.require(toFail: recognizer)
                                }
                                mapView.addGestureRecognizer(mapTapGestureRecognizer)
                                

Note

You are responsible for getting permission to use the map data and for ensuring that your use adheres to the relevant terms of use.

See the Simple map view example to learn how to initialize a basic MGLMapView.

Creating Instances

  • initWithFrame

    Initializes and returns a newly allocated map view with the specified frame and the default style.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithFrame:(CGRect)frame;

    Swift

    init(frame: CGRect)

    Parameters

    frame

    The frame for the view, measured in points.

    Return Value

    An initialized map view.

  • initWithFrame:styleURL:

    Initializes and returns a newly allocated map view with the specified frame and style URL.

    See the Apply a style designed in Mapbox Studio example to learn how to initialize an MGLMapView with a custom style. See the Apply a style designed in Mapbox Studio Classic example to learn how to intialize an MGLMapView with a Studio Classic style or a custom style JSON. See the Use third-party vector tiles example to learn how to initialize an MGLMapView with a third-party tile source.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithFrame:(CGRect)frame
                                                                     styleURL:(nullable NSURL *)styleURL;

    Swift

    init(frame: CGRect, styleURL: URL?)

    Parameters

    frame

    The frame for the view, measured in points.

    styleURL

    URL of the map style to display. The URL may be a full HTTP or HTTPS URL, a canonical URL or a path to a local file relative to the application’s resource path. Specify nil for the default style.

    Return Value

    An initialized map view.

Accessing the Delegate

  • delegate

    The receiver’s delegate.

    A map view sends messages to its delegate to notify it of changes to its contents or the viewpoint. The delegate also provides information about annotations displayed on the map, such as the styles to apply to individual annotations.

    Declaration

    Objective-C

    @property (nonatomic, weak, nullable) id<MGLMapViewDelegate> delegate;

Configuring the Map’s Appearance

  • style

    The style currently displayed in the receiver.

    Unlike the styleURL property, this property is set to an object that allows you to manipulate every aspect of the style locally.

    If the style is loading, this property is set to nil until the style finishes loading. If the style has failed to load, this property is set to nil. Because the style loads asynchronously, you should manipulate it in the -[MGLMapViewDelegate mapView:didFinishLoadingStyle:] or -[MGLMapViewDelegate mapViewDidFinishLoadingMap:] method. It is not possible to manipulate the style before it has finished loading.

    Note

    The default styles provided by Mapbox contain sources and layers with identifiers that will change over time. Applications that use APIs that manipulate a style’s sources and layers must first set the style URL to an explicitly versioned style using a convenience method like +[MGLStyle outdoorsStyleURLWithVersion:], MGLMapView’s “Style URL” inspectable in Interface Builder, or a manually constructed NSURL.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nullable) MGLStyle *style;

    Swift

    var style: MGLStyle? { get }
  • styleURL

    URL of the style currently displayed in the receiver.

    The URL may be a full HTTP or HTTPS URL, canonical URL, or a path to a local file relative to the application’s resource path.

    If you set this property to nil, the receiver will use the default style and this property will automatically be set to that style’s URL.

    If you want to modify the current style without replacing it outright, or if you want to introspect individual style attributes, use the style property.

    See the Switch between map styles example to learn how to change the style of a map at runtime.

    Declaration

    Objective-C

    @property (nonatomic, null_resettable) NSURL *styleURL;

    Swift

    var styleURL: URL! { get set }
  • -reloadStyle:

    Reloads the style.

    You do not normally need to call this method. The map view automatically responds to changes in network connectivity by reloading the style. You may need to call this method if you change the access token after a style has loaded but before loading a style associated with a different Mapbox account.

    This method does not bust the cache. Even if the style has recently changed on the server, calling this method does not necessarily ensure that the map view reflects those changes.

    Declaration

    Objective-C

    - (void)reloadStyle:(nullable id)sender;

    Swift

    @IBAction func reloadStyle(_ sender: Any?)
  • automaticallyAdjustsContentInset

    A boolean value that indicates if whether the map view should automatically adjust its content insets.

    When this property is set to YES the map automatically updates its contentInset property to account for any area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure the map view.

    Declaration

    Objective-C

    @property BOOL automaticallyAdjustsContentInset;

    Swift

    var automaticallyAdjustsContentInset: Bool { get set }
  • showsScale

    A Boolean value indicating whether the map may display scale information.

    The scale bar may not be shown at all zoom levels. The scale bar becomes visible when the maximum distance visible on the map view is less than 400 miles (800 kilometers). The zoom level where this occurs depends on the latitude at the map view’s center coordinate, as well as the device screen width. At latitudes farther from the equator, the scale bar becomes visible at lower zoom levels.

    The unit of measurement is determined by the user’s device locale.

    The view controlled by this property is available at scaleBar. The default value of this property is NO.

    Declaration

    Objective-C

    @property (nonatomic) BOOL showsScale;

    Swift

    var showsScale: Bool { get set }
  • scaleBar

    A control indicating the scale of the map. The scale bar is positioned in the upper-left corner. Enable the scale bar via showsScale.

    Declaration

    Objective-C

    @property (nonatomic, readonly) UIView *_Nonnull scaleBar;

    Swift

    var scaleBar: UIView { get }
  • scaleBarShouldShowDarkStyles

    Sets whether the scale uses styles that make it easier to read on a dark styled map

    Declaration

    Objective-C

    @property (nonatomic) BOOL scaleBarShouldShowDarkStyles;

    Swift

    var scaleBarShouldShowDarkStyles: Bool { get set }
  • scaleBarUsesMetricSystem

    Sets whether the scale uses metric

    Declaration

    Objective-C

    @property (nonatomic) BOOL scaleBarUsesMetricSystem;

    Swift

    var scaleBarUsesMetricSystem: Bool { get set }
  • scaleBarPosition

    The position of the scale bar. The default value is MGLOrnamentPositionTopLeft.

    Declaration

    Objective-C

    @property (nonatomic) MGLOrnamentPosition scaleBarPosition;

    Swift

    var scaleBarPosition: MGLOrnamentPosition { get set }
  • scaleBarMargins

    A CGPoint indicating the position offset of the scale bar.

    Declaration

    Objective-C

    @property (nonatomic) CGPoint scaleBarMargins;

    Swift

    var scaleBarMargins: CGPoint { get set }
  • compassView

    A control indicating the map’s direction and allowing the user to manipulate the direction, positioned in the upper-right corner.

    Declaration

    Objective-C

    @property (nonatomic, readonly) MGLCompassButton *_Nonnull compassView;

    Swift

    var compassView: MGLCompassButton { get }
  • compassViewPosition

    The position of the compass view. The default value is MGLOrnamentPositionTopRight.

    Declaration

    Objective-C

    @property (nonatomic) MGLOrnamentPosition compassViewPosition;

    Swift

    var compassViewPosition: MGLOrnamentPosition { get set }
  • compassViewMargins

    A CGPoint indicating the position offset of the compass.

    Declaration

    Objective-C

    @property (nonatomic) CGPoint compassViewMargins;

    Swift

    var compassViewMargins: CGPoint { get set }
  • logoView

    The Mapbox wordmark, positioned in the lower-left corner.

    Note

    The Mapbox terms of service, which governs the use of Mapbox-hosted vector tiles and styles, requires most Mapbox customers to display the Mapbox wordmark. If this applies to you, do not hide this view or change its contents.

    Declaration

    Objective-C

    @property (nonatomic, readonly) UIImageView *_Nonnull logoView;

    Swift

    var logoView: UIImageView { get }
  • logoViewPosition

    The position of the logo view. The default value is MGLOrnamentPositionBottomLeft.

    Declaration

    Objective-C

    @property (nonatomic) MGLOrnamentPosition logoViewPosition;

    Swift

    var logoViewPosition: MGLOrnamentPosition { get set }
  • logoViewMargins

    A CGPoint indicating the position offset of the logo.

    Declaration

    Objective-C

    @property (nonatomic) CGPoint logoViewMargins;

    Swift

    var logoViewMargins: CGPoint { get set }
  • attributionButton

    A view showing legally required copyright notices, positioned at the bottom-right of the map view.

    If you choose to reimplement this view, assign the -showAttribution: method as the action for your view to present the default notices and settings.

    Note

    The Mapbox terms of service, which governs the use of Mapbox-hosted vector tiles and styles, requires these copyright notices to accompany any map that features Mapbox-designed styles, OpenStreetMap data, or other Mapbox data such as satellite or terrain data. If that applies to this map view, do not hide this view or remove any notices from it.

    Declaration

    Objective-C

    @property (nonatomic, readonly) UIButton *_Nonnull attributionButton;

    Swift

    var attributionButton: UIButton { get }
  • attributionButtonPosition

    The position of the attribution button. The default value is MGLOrnamentPositionBottomRight.

    Declaration

    Objective-C

    @property (nonatomic) MGLOrnamentPosition attributionButtonPosition;

    Swift

    var attributionButtonPosition: MGLOrnamentPosition { get set }
  • attributionButtonMargins

    A CGPoint indicating the position offset of the attribution.

    Declaration

    Objective-C

    @property (nonatomic) CGPoint attributionButtonMargins;

    Swift

    var attributionButtonMargins: CGPoint { get set }
  • -showAttribution:

    Show the attribution action sheet.

    This action is performed when the user taps on the attribution button provided by default via the attributionButton property. If you implement a custom attribution button, you should add this action to the button.

    Declaration

    Objective-C

    - (void)showAttribution:(nonnull id)sender;

    Swift

    @IBAction func showAttribution(_ sender: Any)
  • preferredFramesPerSecond

    The preferred frame rate at which the map view is rendered.

    The default value for this property is MGLMapViewPreferredFramesPerSecondDefault, which will adaptively set the preferred frame rate based on the capability of the user’s device to maintain a smooth experience.

    In addition to the provided MGLMapViewPreferredFramesPerSecond options, this property can be set to arbitrary integer values.

    See

    CADisplayLink.preferredFramesPerSecond

    Declaration

    Objective-C

    @property (nonatomic) MGLMapViewPreferredFramesPerSecond preferredFramesPerSecond;

    Swift

    var preferredFramesPerSecond: MGLMapViewPreferredFramesPerSecond { get set }
  • prefetchesTiles

    A Boolean value indicating whether the map should prefetch tiles.

    When this property is set to YES, the map view prefetches tiles designed for a low zoom level and displays them until receiving more detailed tiles for the current zoom level. The prefetched tiles typically contain simplified versions of each shape, improving the map view’s perceived performance.

    The default value of this property is YES.

    Declaration

    Objective-C

    @property (nonatomic) BOOL prefetchesTiles;

    Swift

    var prefetchesTiles: Bool { get set }

Displaying the User’s Location

  • locationManager

    The object that this map view uses to start and stop the delivery of location-related updates.

    To receive the current user location, implement the -[MGLMapViewDelegate mapView:didUpdateUserLocation:] and -[MGLMapViewDelegate mapView:didFailToLocateUserWithError:] methods.

    If setting this property to nil or if no custom manager is provided this property is set to the default location manager.

    MGLMapView uses a default location manager. If you want to substitute your own location manager, you should do so by setting this property before setting showsUserLocation to YES. To restore the default location manager, set this property to nil.

    Declaration

    Objective-C

    @property (nonatomic, null_resettable) id<MGLLocationManager> locationManager;
  • showsUserLocation

    A Boolean value indicating whether the map may display the user location.

    Setting this property to YES causes the map view to use the Core Location framework to find the current location. As long as this property is YES, the map view continues to track the user’s location and update it periodically.

    This property does not indicate whether the user’s position is actually visible on the map, only whether the map view is allowed to display it. To determine whether the user’s position is visible, use the userLocationVisible property. The default value of this property is NO.

    Your app must specify a value for NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in its Info.plist to satisfy the requirements of the underlying Core Location framework when enabling this property.

    If you implement a custom location manager, set the locationManager before calling showsUserLocation.

    Declaration

    Objective-C

    @property (nonatomic) BOOL showsUserLocation;

    Swift

    var showsUserLocation: Bool { get set }
  • userLocationVisible

    A Boolean value indicating whether the device’s current location is visible in the map view.

    Use showsUserLocation to control the visibility of the on-screen user location annotation.

    Declaration

    Objective-C

    @property (nonatomic, assign, unsafe_unretained, readonly,
                                                  getter=isUserLocationVisible) BOOL userLocationVisible;

    Swift

    var isUserLocationVisible: Bool { get }
  • userLocation

    Returns the annotation object indicating the user’s current location.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nullable) MGLUserLocation *userLocation;

    Swift

    var userLocation: MGLUserLocation? { get }
  • userTrackingMode

    The mode used to track the user location. The default value is MGLUserTrackingModeNone.

    Changing the value of this property updates the map view with an animated transition. If you don’t want to animate the change, use the -setUserTrackingMode:animated: method instead.

    See the Customize the user location annotation to learn how to customize the default user location annotation shown by MGLUserTrackingMode.

    Declaration

    Objective-C

    @property (nonatomic) MGLUserTrackingMode userTrackingMode;

    Swift

    var userTrackingMode: MGLUserTrackingMode { get set }
  • -setUserTrackingMode:animated:

    Deprecated. Sets the mode used to track the user location, with an optional transition.

    To specify a completion handler to execute after the animation finishes, use the -setUserTrackingMode:animated:completionHandler: method.

    Declaration

    Objective-C

    - (void)setUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated;

    Swift

    func setUserTrackingMode(_ mode: MGLUserTrackingMode, animated: Bool)

    Parameters

    mode

    The mode used to track the user location.

    animated

    If YES, there is an animated transition from the current viewport to a viewport that results from the change to mode. If NO, the map view instantaneously changes to the new viewport. This parameter only affects the initial transition; subsequent changes to the user location or heading are always animated.

  • -setUserTrackingMode:animated:completionHandler:

    Sets the mode used to track the user location, with an optional transition and completion handler.

    Declaration

    Objective-C

    - (void)setUserTrackingMode:(MGLUserTrackingMode)mode
                                                           animated:(BOOL)animated
                                                  completionHandler:(nullable void (^)(void))completion;

    Swift

    func setUserTrackingMode(_ mode: MGLUserTrackingMode, animated: Bool) async

    Parameters

    mode

    The mode used to track the user location.

    animated

    If YES, there is an animated transition from the current viewport to a viewport that results from the change to mode. If NO, the map view instantaneously changes to the new viewport. This parameter only affects the initial transition; subsequent changes to the user location or heading are always animated.

    completion

    The block executed after the animation finishes.

  • userLocationVerticalAlignment

    The vertical alignment of the user location annotation within the receiver. The default value is MGLAnnotationVerticalAlignmentCenter.

    Changing the value of this property updates the map view with an animated transition. If you don’t want to animate the change, use the -setUserLocationVerticalAlignment:animated: method instead.

    Declaration

    Objective-C

    @property (nonatomic) MGLAnnotationVerticalAlignment userLocationVerticalAlignment;

    Swift

    var userLocationVerticalAlignment: MGLAnnotationVerticalAlignment { get set }
  • -setUserLocationVerticalAlignment:animated:

    Sets the vertical alignment of the user location annotation within the receiver, with an optional transition.

    Declaration

    Objective-C

    - (void)setUserLocationVerticalAlignment:
                                                    (MGLAnnotationVerticalAlignment)alignment
                                                                        animated:(BOOL)animated;

    Swift

    func setUserLocationVerticalAlignment(_ alignment: MGLAnnotationVerticalAlignment, animated: Bool)

    Parameters

    alignment

    The vertical alignment of the user location annotation.

    animated

    If YES, the user location annotation animates to its new position within the map view. If NO, the user location annotation instantaneously moves to its new position.

  • -updateUserLocationAnnotationView

    Updates the position of the user location annotation view by retreiving the user’s last known location.

    Declaration

    Objective-C

    - (void)updateUserLocationAnnotationView;

    Swift

    func updateUserLocationAnnotationView()
  • -updateUserLocationAnnotationViewAnimatedWithDuration:

    Updates the position of the user location annotation view by retreiving the user’s last known location with a specified duration.

    Declaration

    Objective-C

    - (void)updateUserLocationAnnotationViewAnimatedWithDuration:
                                            (NSTimeInterval)duration;

    Swift

    func updateUserLocationAnnotationViewAnimated(withDuration duration: TimeInterval)

    Parameters

    duration

    The duration to animate the change in seconds.

  • showsUserHeadingIndicator

    A Boolean value indicating whether the user location annotation may display a permanent heading indicator.

    Setting this property to YES causes the default user location annotation to appear and always show an arrow-shaped heading indicator, if heading is available. This property does not rotate the map; for that, see MGLUserTrackingModeFollowWithHeading.

    This property has no effect when userTrackingMode is MGLUserTrackingModeFollowWithHeading or MGLUserTrackingModeFollowWithCourse.

    The default value of this property is NO.

    Declaration

    Objective-C

    @property (nonatomic) BOOL showsUserHeadingIndicator;

    Swift

    var showsUserHeadingIndicator: Bool { get set }
  • displayHeadingCalibration

    Whether the map view should display a heading calibration alert when necessary. The default value is YES.

    Declaration

    Objective-C

    @property (nonatomic) BOOL displayHeadingCalibration;

    Swift

    var displayHeadingCalibration: Bool { get set }
  • targetCoordinate

    The geographic coordinate that is the subject of observation as the user location is being tracked.

    By default, this property is set to an invalid coordinate, indicating that there is no target. In course tracking mode, the target forms one of two foci in the viewport, the other being the user location annotation. Typically, this property is set to a destination or waypoint in a real-time navigation scene. As the user annotation moves toward the target, the map automatically zooms in to fit both foci optimally within the viewport.

    This property has no effect if the userTrackingMode property is set to a value other than MGLUserTrackingModeFollowWithCourse.

    Changing the value of this property updates the map view with an animated transition. If you don’t want to animate the change, use the -setTargetCoordinate:animated: method instead.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationCoordinate2D targetCoordinate;

    Swift

    var targetCoordinate: CLLocationCoordinate2D { get set }
  • -setTargetCoordinate:animated:

    Deprecated. Sets the geographic coordinate that is the subject of observation as the user location is being tracked, with an optional transition animation.

    By default, the target coordinate is set to an invalid coordinate, indicating that there is no target. In course tracking mode, the target forms one of two foci in the viewport, the other being the user location annotation. Typically, the target is set to a destination or waypoint in a real-time navigation scene. As the user annotation moves toward the target, the map automatically zooms in to fit both foci optimally within the viewport.

    This method has no effect if the userTrackingMode property is set to a value other than MGLUserTrackingModeFollowWithCourse.

    To specify a completion handler to execute after the animation finishes, use the -setTargetCoordinate:animated:completionHandler: method.

    Declaration

    Objective-C

    - (void)setTargetCoordinate:(CLLocationCoordinate2D)targetCoordinate
                                                           animated:(BOOL)animated;

    Swift

    func setTargetCoordinate(_ targetCoordinate: CLLocationCoordinate2D, animated: Bool)

    Parameters

    targetCoordinate

    The target coordinate to fit within the viewport.

    animated

    If YES, the map animates to fit the target within the map view. If NO, the map fits the target instantaneously.

  • -setTargetCoordinate:animated:completionHandler:

    Sets the geographic coordinate that is the subject of observation as the user location is being tracked, with an optional transition animation and completion handler.

    By default, the target coordinate is set to an invalid coordinate, indicating that there is no target. In course tracking mode, the target forms one of two foci in the viewport, the other being the user location annotation. Typically, the target is set to a destination or waypoint in a real-time navigation scene. As the user annotation moves toward the target, the map automatically zooms in to fit both foci optimally within the viewport.

    This method has no effect if the userTrackingMode property is set to a value other than MGLUserTrackingModeFollowWithCourse.

    Declaration

    Objective-C

    - (void)setTargetCoordinate:(CLLocationCoordinate2D)targetCoordinate
                                                           animated:(BOOL)animated
                                                  completionHandler:(nullable void (^)(void))completion;

    Swift

    func setTargetCoordinate(_ targetCoordinate: CLLocationCoordinate2D, animated: Bool) async

    Parameters

    targetCoordinate

    The target coordinate to fit within the viewport.

    animated

    If YES, the map animates to fit the target within the map view. If NO, the map fits the target instantaneously.

    completion

    The block executed after the animation finishes.

Configuring How the User Interacts with the Map

  • zoomEnabled

    A Boolean value that determines whether the user may zoom the map in and out, changing the zoom level.

    When this property is set to YES, the default, the user may zoom the map in and out by pinching two fingers or by double tapping, holding, and moving the finger up and down.

    This property controls only user interactions with the map. If you set the value of this property to NO, you may still change the map zoom programmatically.

    Declaration

    Objective-C

    @property (nonatomic, getter=isZoomEnabled) BOOL zoomEnabled;

    Swift

    var isZoomEnabled: Bool { get set }
  • scrollEnabled

    A Boolean value that determines whether the user may scroll around the map, changing the center coordinate.

    When this property is set to YES, the default, the user may scroll the map by dragging or swiping with one finger.

    This property controls only user interactions with the map. If you set the value of this property to NO, you may still change the map location programmatically.

    Declaration

    Objective-C

    @property (nonatomic, assign, unsafe_unretained, readwrite,
                                                  getter=isScrollEnabled) BOOL scrollEnabled;

    Swift

    var isScrollEnabled: Bool { get set }
  • panScrollingMode

    The scrolling mode the user is allowed to use to interact with the map.

    MGLPanScrollingModeHorizontal only allows the user to scroll horizontally on the map, restricting a user’s ability to scroll vertically. MGLPanScrollingModeVertical only allows the user to scroll vertically on the map, restricting a user’s ability to scroll horizontally. MGLPanScrollingModeDefault allows the user to scroll both horizontally and vertically on the map.

    By default, this property is set to MGLPanScrollingModeDefault.

    Declaration

    Objective-C

    @property (nonatomic) MGLPanScrollingMode panScrollingMode;

    Swift

    var panScrollingMode: MGLPanScrollingMode { get set }
  • rotateEnabled

    A Boolean value that determines whether the user may rotate the map, changing the direction.

    When this property is set to YES, the default, the user may rotate the map by moving two fingers in a circular motion.

    This property controls only user interactions with the map. If you set the value of this property to NO, you may still rotate the map programmatically.

    Declaration

    Objective-C

    @property (nonatomic, assign, unsafe_unretained, readwrite,
                                                  getter=isRotateEnabled) BOOL rotateEnabled;

    Swift

    var isRotateEnabled: Bool { get set }
  • pitchEnabled

    A Boolean value that determines whether the user may change the pitch (tilt) of the map.

    When this property is set to YES, the default, the user may tilt the map by vertically dragging two fingers.

    This property controls only user interactions with the map. If you set the value of this property to NO, you may still change the pitch of the map programmatically.

    The default value of this property is YES.

    Declaration

    Objective-C

    @property (nonatomic, assign, unsafe_unretained, readwrite,
                                                  getter=isPitchEnabled) BOOL pitchEnabled;

    Swift

    var isPitchEnabled: Bool { get set }
  • anchorRotateOrZoomGesturesToCenterCoordinate

    A Boolean value that determines whether gestures are anchored to the center coordinate of the map while rotating or zooming. Default value is set to NO.

    Declaration

    Objective-C

    @property (nonatomic) BOOL anchorRotateOrZoomGesturesToCenterCoordinate;

    Swift

    var anchorRotateOrZoomGesturesToCenterCoordinate: Bool { get set }
  • hapticFeedbackEnabled

    A Boolean value that determines whether the user will receive haptic feedback for certain interactions with the map.

    When this property is set to YES, the default, a UIImpactFeedbackStyleLight haptic feedback event be played when the user rotates the map to due north (0°).

    This feature requires a device that supports haptic feedback, running iOS 10 or newer.

    Declaration

    Objective-C

    @property (nonatomic, assign, unsafe_unretained, readwrite,
                                                  getter=isHapticFeedbackEnabled) BOOL hapticFeedbackEnabled;

    Swift

    var isHapticFeedbackEnabled: Bool { get set }
  • decelerationRate

    A floating-point value that determines the rate of deceleration after the user lifts their finger.

    Your application can use the MGLMapViewDecelerationRateNormal and MGLMapViewDecelerationRateFast constants as reference points for reasonable deceleration rates. MGLMapViewDecelerationRateImmediate can be used to disable deceleration entirely.

    Declaration

    Objective-C

    @property (nonatomic) CGFloat decelerationRate;

    Swift

    var decelerationRate: CGFloat { get set }

Manipulating the Viewpoint

  • centerCoordinate

    The geographic coordinate at the center of the map view.

    Changing the value of this property centers the map on the new coordinate without changing the current zoom level.

    Changing the value of this property updates the map view immediately. If you want to animate the change, use the -setCenterCoordinate:animated: method instead.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationCoordinate2D centerCoordinate;

    Swift

    var centerCoordinate: CLLocationCoordinate2D { get set }
  • -setCenterCoordinate:animated:

    Changes the center coordinate of the map and optionally animates the change.

    Changing the center coordinate centers the map on the new coordinate without changing the current zoom level. For animated changes, wait until the map view has finished loading before calling this method.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification.

    Declaration

    Objective-C

    - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate
                                                           animated:(BOOL)animated;

    Swift

    func setCenter(_ coordinate: CLLocationCoordinate2D, animated: Bool)

    Parameters

    coordinate

    The new center coordinate for the map.

    animated

    Specify YES if you want the map view to scroll to the new location or NO if you want the map to display the new location immediately.

  • -setCenterCoordinate:zoomLevel:animated:

    Changes the center coordinate and zoom level of the map and optionally animates the change. For animated changes, wait until the map view has finished loading before calling this method.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification.

    Declaration

    Objective-C

    - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                          zoomLevel:(double)zoomLevel
                                                           animated:(BOOL)animated;

    Swift

    func setCenter(_ centerCoordinate: CLLocationCoordinate2D, zoomLevel: Double, animated: Bool)

    Parameters

    centerCoordinate

    The new center coordinate for the map.

    zoomLevel

    The new zoom level for the map.

    animated

    Specify YES if you want the map view to animate scrolling and zooming to the new location or NO if you want the map to display the new location immediately.

  • setCenterCoordinate:zoomLevel:direction:animated:

    Changes the center coordinate, zoom level, and direction of the map and optionally animates the change. For animated changes, wait until the map view has finished loading before calling this method.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification.

    Declaration

    Objective-C

    - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                          zoomLevel:(double)zoomLevel
                                                          direction:(CLLocationDirection)direction
                                                           animated:(BOOL)animated;

    Swift

    func setCenter(_ centerCoordinate: CLLocationCoordinate2D, zoomLevel: Double, direction: CLLocationDirection, animated: Bool)

    Parameters

    centerCoordinate

    The new center coordinate for the map.

    zoomLevel

    The new zoom level for the map.

    direction

    The new direction for the map, measured in degrees relative to true north. A negative value leaves the map’s direction unchanged.

    animated

    Specify YES if you want the map view to animate scrolling, zooming, and rotating to the new location or NO if you want the map to display the new location immediately.

  • -setCenterCoordinate:zoomLevel:direction:animated:completionHandler:

    Changes the center coordinate, zoom level, and direction of the map, calling a completion handler at the end of an optional animation. For animated changes, wait until the map view has finished loading before calling this method.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification.

    Declaration

    Objective-C

    - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                                          zoomLevel:(double)zoomLevel
                                                          direction:(CLLocationDirection)direction
                                                           animated:(BOOL)animated
                                                  completionHandler:(nullable void (^)(void))completion;

    Swift

    func setCenter(_ centerCoordinate: CLLocationCoordinate2D, zoomLevel: Double, direction: CLLocationDirection, animated: Bool) async

    Parameters

    centerCoordinate

    The new center coordinate for the map.

    zoomLevel

    The new zoom level for the map.

    direction

    The new direction for the map, measured in degrees relative to true north. A negative value leaves the map’s direction unchanged.

    animated

    Specify YES if you want the map view to animate scrolling, zooming, and rotating to the new location or NO if you want the map to display the new location immediately.

    completion

    The block executed after the animation finishes.

  • zoomLevel

    The zoom level of the receiver.

    In addition to affecting the visual size and detail of features on the map, the zoom level affects the size of the vector tiles that are loaded. At zoom level 0, each tile covers the entire world map; at zoom level 1, it covers ¼ of the world; at zoom level 2, 116 of the world, and so on.

    Changing the value of this property updates the map view immediately. If you want to animate the change, use the -setZoomLevel:animated: method instead.

    Declaration

    Objective-C

    @property (nonatomic) double zoomLevel;

    Swift

    var zoomLevel: Double { get set }
  • -setZoomLevel:animated:

    Changes the zoom level of the map and optionally animates the change.

    Changing the zoom level scales the map without changing the current center coordinate.

    Declaration

    Objective-C

    - (void)setZoomLevel:(double)zoomLevel animated:(BOOL)animated;

    Swift

    func setZoomLevel(_ zoomLevel: Double, animated: Bool)

    Parameters

    zoomLevel

    The new zoom level for the map.

    animated

    Specify YES if you want the map view to animate the change to the new zoom level or NO if you want the map to display the new zoom level immediately.

  • minimumZoomLevel

    The minimum zoom level at which the map can be shown.

    Depending on the map view’s aspect ratio, the map view may be prevented from reaching the minimum zoom level, in order to keep the map from repeating within the current viewport.

    If the value of this property is greater than that of the maximumZoomLevel property, the behavior is undefined.

    The default minimumZoomLevel is 0.

    Declaration

    Objective-C

    @property (nonatomic) double minimumZoomLevel;

    Swift

    var minimumZoomLevel: Double { get set }
  • maximumZoomLevel

    The maximum zoom level the map can be shown at.

    If the value of this property is smaller than that of the minimumZoomLevel property, the behavior is undefined.

    The default maximumZoomLevel is 22. The upper bound for this property is 25.5.

    Declaration

    Objective-C

    @property (nonatomic) double maximumZoomLevel;

    Swift

    var maximumZoomLevel: Double { get set }
  • direction

    The heading of the map, measured in degrees clockwise from true north.

    The value 0 means that the top edge of the map view corresponds to true north. The value 90 means the top of the map is pointing due east. The value 180 means the top of the map points due south, and so on.

    Changing the value of this property updates the map view immediately. If you want to animate the change, use the -setDirection:animated: method instead.

    Declaration

    Objective-C

    @property (nonatomic) CLLocationDirection direction;

    Swift

    var direction: CLLocationDirection { get set }
  • -setDirection:animated:

    Changes the heading of the map and optionally animates the change.

    Changing the heading rotates the map without changing the current center coordinate or zoom level.

    Declaration

    Objective-C

    - (void)setDirection:(CLLocationDirection)direction animated:(BOOL)animated;

    Swift

    func setDirection(_ direction: CLLocationDirection, animated: Bool)

    Parameters

    direction

    The heading of the map, measured in degrees clockwise from true north.

    animated

    Specify YES if you want the map view to animate the change to the new heading or NO if you want the map to display the new heading immediately.

  • minimumPitch

    The minimum pitch of the map’s camera toward the horizon measured in degrees.

    If the value of this property is greater than that of the maximumPitch property, the behavior is undefined. The pitch may not be less than 0 regardless of this property.

    The default value of this property is 0 degrees, allowing the map to appear two-dimensional.

    Declaration

    Objective-C

    @property (nonatomic) CGFloat minimumPitch;

    Swift

    var minimumPitch: CGFloat { get set }
  • maximumPitch

    The maximum pitch of the map’s camera toward the horizon measured in degrees.

    If the value of this property is smaller than that of the minimumPitch property, the behavior is undefined. The pitch may not exceed 60 degrees regardless of this property.

    The default value of this property is 60 degrees.

    Declaration

    Objective-C

    @property (nonatomic) CGFloat maximumPitch;

    Swift

    var maximumPitch: CGFloat { get set }
  • -resetNorth

    Resets the map rotation to a northern heading — a direction of 0 degrees.

    Declaration

    Objective-C

    - (void)resetNorth;

    Swift

    @IBAction func resetNorth()
  • -resetPosition

    Resets the map to the current style’s default viewport.

    If the style doesn’t specify a default viewport, the map resets to a minimum zoom level, a center coordinate of (0, 0), and a northern heading.

    Declaration

    Objective-C

    - (void)resetPosition;

    Swift

    @IBAction func resetPosition()
  • visibleCoordinateBounds

    The coordinate bounds visible in the receiver’s viewport.

    Changing the value of this property updates the receiver immediately. If you want to animate the change, call -setVisibleCoordinateBounds:animated: instead.

    If a longitude is less than −180 degrees or greater than 180 degrees, the visible bounds straddles the antimeridian or international date line. For example, if both Tokyo and San Francisco are visible, the visible bounds might extend from (35.68476, −220.24257) to (37.78428, −122.41310).

    Declaration

    Objective-C

    @property (nonatomic) MGLCoordinateBounds visibleCoordinateBounds;

    Swift

    var visibleCoordinateBounds: MGLCoordinateBounds { get set }
  • -setVisibleCoordinateBounds:animated:

    Changes the receiver’s viewport to fit the given coordinate bounds, optionally animating the change.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible bounds to extend from (35.68476, −220.24257) to (37.78428, −122.41310).

    Declaration

    Objective-C

    - (void)setVisibleCoordinateBounds:(MGLCoordinateBounds)bounds
                                                                  animated:(BOOL)animated;

    Swift

    func setVisibleCoordinateBounds(_ bounds: MGLCoordinateBounds, animated: Bool)

    Parameters

    bounds

    The bounds that the viewport will show in its entirety.

    animated

    Specify YES to animate the change by smoothly scrolling and zooming or NO to immediately display the given bounds.

  • -setVisibleCoordinateBounds:edgePadding:animated:

    Deprecated. Changes the receiver’s viewport to fit the given coordinate bounds with some additional padding on each side.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible bounds to extend from (35.68476, −220.24257) to (37.78428, −122.41310).

    To specify a completion handler to execute after the animation finishes, use the -setVisibleCoordinateBounds:edgePadding:animated:completionHandler: method.

    Declaration

    Objective-C

    - (void)setVisibleCoordinateBounds:(MGLCoordinateBounds)bounds
                                                               edgePadding:(UIEdgeInsets)insets
                                                                  animated:(BOOL)animated;

    Swift

    func setVisibleCoordinateBounds(_ bounds: MGLCoordinateBounds, edgePadding insets: UIEdgeInsets, animated: Bool)

    Parameters

    bounds

    The bounds that the viewport will show in its entirety.

    insets

    The minimum padding (in screen points) that will be visible around the given coordinate bounds.

    animated

    Specify YES to animate the change by smoothly scrolling and zooming or NO to immediately display the given bounds.

  • -setVisibleCoordinateBounds:edgePadding:animated:completionHandler:

    Changes the receiver’s viewport to fit the given coordinate bounds with some additional padding on each side, optionally calling a completion handler.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible bounds to extend from (35.68476, −220.24257) to (37.78428, −122.41310).

    Declaration

    Objective-C

    - (void)setVisibleCoordinateBounds:(MGLCoordinateBounds)bounds
                                                               edgePadding:(UIEdgeInsets)insets
                                                                  animated:(BOOL)animated
                                                         completionHandler:(nullable void (^)(void))completion;

    Swift

    func setVisibleCoordinateBounds(_ bounds: MGLCoordinateBounds, edgePadding insets: UIEdgeInsets, animated: Bool) async

    Parameters

    bounds

    The bounds that the viewport will show in its entirety.

    insets

    The minimum padding (in screen points) that will be visible around the given coordinate bounds.

    animated

    Specify YES to animate the change by smoothly scrolling and zooming or NO to immediately display the given bounds.

    completion

    The block executed after the animation finishes.

  • -setVisibleCoordinates:count:edgePadding:animated:

    Changes the receiver’s viewport to fit all of the given coordinates with some additional padding on each side.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible coordinates to (35.68476, −220.24257) and (37.78428, −122.41310).

    Declaration

    Objective-C

    - (void)setVisibleCoordinates:
                                                    (nonnull const CLLocationCoordinate2D *)coordinates
                                                                count:(NSUInteger)count
                                                          edgePadding:(UIEdgeInsets)insets
                                                             animated:(BOOL)animated;

    Swift

    func setVisibleCoordinates(_ coordinates: UnsafePointer<CLLocationCoordinate2D>, count: UInt, edgePadding insets: UIEdgeInsets, animated: Bool)

    Parameters

    coordinates

    The coordinates that the viewport will show.

    count

    The number of coordinates. This number must not be greater than the number of elements in coordinates.

    insets

    The minimum padding (in screen points) that will be visible around the given coordinate bounds.

    animated

    Specify YES to animate the change by smoothly scrolling and zooming or NO to immediately display the given bounds.

  • -setVisibleCoordinates:count:edgePadding:direction:duration:animationTimingFunction:completionHandler:

    Changes the receiver’s viewport to fit all of the given coordinates with some additional padding on each side, optionally calling a completion handler.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible coordinates to (35.68476, −220.24257) and (37.78428, −122.41310).

    Declaration

    Objective-C

    - (void)setVisibleCoordinates:
                                                    (nonnull const CLLocationCoordinate2D *)coordinates
                                                                count:(NSUInteger)count
                                                          edgePadding:(UIEdgeInsets)insets
                                                            direction:(CLLocationDirection)direction
                                                             duration:(NSTimeInterval)duration
                                              animationTimingFunction:(nullable CAMediaTimingFunction *)function
                                                    completionHandler:(nullable void (^)(void))completion;

    Swift

    func setVisibleCoordinates(_ coordinates: UnsafePointer<CLLocationCoordinate2D>, count: UInt, edgePadding insets: UIEdgeInsets, direction: CLLocationDirection, duration: TimeInterval, animationTimingFunction function: CAMediaTimingFunction?) async

    Parameters

    coordinates

    The coordinates that the viewport will show.

    count

    The number of coordinates. This number must not be greater than the number of elements in coordinates.

    insets

    The minimum padding (in screen points) that will be visible around the given coordinate bounds.

    direction

    The direction to rotate the map to, measured in degrees relative to true north. A negative value leaves the map’s direction unchanged.

    duration

    The duration to animate the change in seconds.

    function

    The timing function to animate the change.

    completion

    The block executed after the animation finishes.

  • -showAnnotations:animated:

    Sets the visible region so that the map displays the specified annotations.

    Calling this method updates the value in the visibleCoordinateBounds property and potentially other properties to reflect the new map region. A small amount of padding is reserved around the edges of the map view. To specify a different amount of padding, use the -showAnnotations:edgePadding:animated: method.

    Declaration

    Objective-C

    - (void)showAnnotations:(nonnull NSArray<id<MGLAnnotation>> *)annotations
                                                       animated:(BOOL)animated;

    Parameters

    annotations

    The annotations that you want to be visible in the map.

    animated

    YES if you want the map region change to be animated, or NO if you want the map to display the new region immediately without animations.

  • -showAnnotations:edgePadding:animated:

    Deprecated. Sets the visible region so that the map displays the specified annotations with the specified amount of padding on each side.

    Calling this method updates the value in the visibleCoordinateBounds property and potentially other properties to reflect the new map region.

    To specify a completion handler to execute after the animation finishes, use the -showAnnotations:edgePadding:animated:completionHandler: method.

    Declaration

    Objective-C

    - (void)showAnnotations:(nonnull NSArray<id<MGLAnnotation>> *)annotations
                                                    edgePadding:(UIEdgeInsets)insets
                                                       animated:(BOOL)animated;

    Parameters

    annotations

    The annotations that you want to be visible in the map.

    insets

    The minimum padding (in screen points) around the edges of the map view to keep clear of annotations.

    animated

    YES if you want the map region change to be animated, or NO if you want the map to display the new region immediately without animations.

  • -showAnnotations:edgePadding:animated:completionHandler:

    Sets the visible region so that the map displays the specified annotations with the specified amount of padding on each side and an optional completion handler.

    Calling this method updates the value in the visibleCoordinateBounds property and potentially other properties to reflect the new map region.

    Declaration

    Objective-C

    - (void)showAnnotations:(nonnull NSArray<id<MGLAnnotation>> *)annotations
                                                    edgePadding:(UIEdgeInsets)insets
                                                       animated:(BOOL)animated
                                              completionHandler:(nullable void (^)(void))completion;

    Parameters

    annotations

    The annotations that you want to be visible in the map.

    insets

    The minimum padding (in screen points) around the edges of the map view to keep clear of annotations.

    animated

    YES if you want the map region change to be animated, or NO if you want the map to display the new region immediately without animations.

    completion

    The block executed after the animation finishes.

  • camera

    A camera representing the current viewpoint of the map.

    Declaration

    Objective-C

    @property (nonatomic, copy) MGLMapCamera *_Nonnull camera;

    Swift

    @NSCopying var camera: MGLMapCamera { get set }
  • -setCamera:animated:

    Moves the viewpoint to a different location with respect to the map with an optional transition animation. For animated changes, wait until the map view has finished loading before calling this method.

    See the Camera animation example to learn how to trigger an animation that rotates around a central point.

    Declaration

    Objective-C

    - (void)setCamera:(nonnull MGLMapCamera *)camera animated:(BOOL)animated;

    Swift

    func setCamera(_ camera: MGLMapCamera, animated: Bool)

    Parameters

    camera

    The new viewpoint.

    animated

    Specify YES if you want the map view to animate the change to the new viewpoint or NO if you want the map to display the new viewpoint immediately.

  • -setCamera:withDuration:animationTimingFunction:

    Moves the viewpoint to a different location with respect to the map with an optional transition duration and timing function. For animated changes, wait until the map view has finished loading before calling this method.

    See the Camera animation example to learn how to create a timed animation that rotates around a central point for a specific duration.

    Declaration

    Objective-C

    - (void)setCamera:(nonnull MGLMapCamera *)camera
                                                       withDuration:(NSTimeInterval)duration
                                            animationTimingFunction:(nullable CAMediaTimingFunction *)function;

    Swift

    func setCamera(_ camera: MGLMapCamera, withDuration duration: TimeInterval, animationTimingFunction function: CAMediaTimingFunction?)

    Parameters

    camera

    The new viewpoint.

    duration

    The amount of time, measured in seconds, that the transition animation should take. Specify 0 to jump to the new viewpoint instantaneously.

    function

    A timing function used for the animation. Set this parameter to nil for a transition that matches most system animations. If the duration is 0, this parameter is ignored.

  • -setCamera:withDuration:animationTimingFunction:completionHandler:

    Moves the viewpoint to a different location with respect to the map with an optional transition duration and timing function. For animated changes, wait until the map view has finished loading before calling this method.

    Declaration

    Objective-C

    - (void)setCamera:(nonnull MGLMapCamera *)camera
                                                       withDuration:(NSTimeInterval)duration
                                            animationTimingFunction:(nullable CAMediaTimingFunction *)function
                                                  completionHandler:(nullable void (^)(void))completion;

    Swift

    func setCamera(_ camera: MGLMapCamera, withDuration duration: TimeInterval, animationTimingFunction function: CAMediaTimingFunction?) async

    Parameters

    camera

    The new viewpoint.

    duration

    The amount of time, measured in seconds, that the transition animation should take. Specify 0 to jump to the new viewpoint instantaneously.

    function

    A timing function used for the animation. Set this parameter to nil for a transition that matches most system animations. If the duration is 0, this parameter is ignored.

    completion

    The block to execute after the animation finishes.

  • -setCamera:withDuration:animationTimingFunction:edgePadding:completionHandler:

    Moves the viewpoint to a different location with respect to the map with an optional transition duration and timing function, and optionally some additional padding on each side. For animated changes, wait until the map view has finished loading before calling this method.

    Declaration

    Objective-C

    - (void)setCamera:(nonnull MGLMapCamera *)camera
                                                       withDuration:(NSTimeInterval)duration
                                            animationTimingFunction:(nullable CAMediaTimingFunction *)function
                                                        edgePadding:(UIEdgeInsets)edgePadding
                                                  completionHandler:(nullable void (^)(void))completion;

    Swift

    func setCamera(_ camera: MGLMapCamera, withDuration duration: TimeInterval, animationTimingFunction function: CAMediaTimingFunction?, edgePadding: UIEdgeInsets) async

    Parameters

    camera

    The new viewpoint.

    duration

    The amount of time, measured in seconds, that the transition animation should take. Specify 0 to jump to the new viewpoint instantaneously.

    function

    A timing function used for the animation. Set this parameter to nil for a transition that matches most system animations. If the duration is 0, this parameter is ignored.

    edgePadding

    The minimum padding (in screen points) that would be visible around the returned camera object if it were set as the receiver’s camera.

    completion

    The block to execute after the animation finishes.

  • -flyToCamera:completionHandler:

    Moves the viewpoint to a different location using a transition animation that evokes powered flight and a default duration based on the length of the flight path.

    The transition animation seamlessly incorporates zooming and panning to help the user find his or her bearings even after traversing a great distance.

    Declaration

    Objective-C

    - (void)flyToCamera:(nonnull MGLMapCamera *)camera
                                            completionHandler:(nullable void (^)(void))completion;

    Swift

    func fly(to camera: MGLMapCamera) async

    Parameters

    camera

    The new viewpoint.

    completion

    The block to execute after the animation finishes.

  • -flyToCamera:withDuration:completionHandler:

    Moves the viewpoint to a different location using a transition animation that evokes powered flight and an optional transition duration.

    The transition animation seamlessly incorporates zooming and panning to help the user find his or her bearings even after traversing a great distance.

    Declaration

    Objective-C

    - (void)flyToCamera:(nonnull MGLMapCamera *)camera
                                                 withDuration:(NSTimeInterval)duration
                                            completionHandler:(nullable void (^)(void))completion;

    Swift

    func fly(to camera: MGLMapCamera, withDuration duration: TimeInterval) async

    Parameters

    camera

    The new viewpoint.

    duration

    The amount of time, measured in seconds, that the transition animation should take. Specify 0 to jump to the new viewpoint instantaneously. Specify a negative value to use the default duration, which is based on the length of the flight path.

    completion

    The block to execute after the animation finishes.

  • -flyToCamera:withDuration:peakAltitude:completionHandler:

    Moves the viewpoint to a different location using a transition animation that evokes powered flight and an optional transition duration and peak altitude.

    The transition animation seamlessly incorporates zooming and panning to help the user find his or her bearings even after traversing a great distance.

    Declaration

    Objective-C

    - (void)flyToCamera:(nonnull MGLMapCamera *)camera
                                                 withDuration:(NSTimeInterval)duration
                                                 peakAltitude:(CLLocationDistance)peakAltitude
                                            completionHandler:(nullable void (^)(void))completion;

    Swift

    func fly(to camera: MGLMapCamera, withDuration duration: TimeInterval, peakAltitude: CLLocationDistance) async

    Parameters

    camera

    The new viewpoint.

    duration

    The amount of time, measured in seconds, that the transition animation should take. Specify 0 to jump to the new viewpoint instantaneously. Specify a negative value to use the default duration, which is based on the length of the flight path.

    peakAltitude

    The altitude, measured in meters, at the midpoint of the animation. The value of this parameter is ignored if it is negative or if the animation transition resulting from a similar call to -setCamera:animated: would have a midpoint at a higher altitude.

    completion

    The block to execute after the animation finishes.

  • -cameraThatFitsCoordinateBounds:

    Returns the camera that best fits the given coordinate bounds.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification; you may receive a nil return value depending on the order of notification delivery.

    Declaration

    Objective-C

    - (nonnull MGLMapCamera *)cameraThatFitsCoordinateBounds:
                                            (MGLCoordinateBounds)bounds;

    Swift

    func cameraThatFitsCoordinateBounds(_ bounds: MGLCoordinateBounds) -> MGLMapCamera

    Parameters

    bounds

    The coordinate bounds to fit to the receiver’s viewport.

    Return Value

    A camera object centered on the same location as the coordinate bounds with zoom level as high (close to the ground) as possible while still including the entire coordinate bounds. The camera object uses the current direction and pitch.

  • -cameraThatFitsCoordinateBounds:edgePadding:

    Returns the camera that best fits the given coordinate bounds with some additional padding on each side.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification; you may receive a nil return value depending on the order of notification delivery.

    Declaration

    Objective-C

    - (nonnull MGLMapCamera *)cameraThatFitsCoordinateBounds:
                                                                      (MGLCoordinateBounds)bounds
                                                                                     edgePadding:(UIEdgeInsets)insets;

    Swift

    func cameraThatFitsCoordinateBounds(_ bounds: MGLCoordinateBounds, edgePadding insets: UIEdgeInsets) -> MGLMapCamera

    Parameters

    bounds

    The coordinate bounds to fit to the receiver’s viewport.

    insets

    The minimum padding (in screen points) that would be visible around the returned camera object if it were set as the receiver’s camera.

    Return Value

    A camera object centered on the same location as the coordinate bounds with zoom level as high (close to the ground) as possible while still including the entire coordinate bounds. The camera object uses the current direction and pitch.

  • -camera:fittingCoordinateBounds:edgePadding:

    Returns the camera that best fits the given coordinate bounds with some additional padding on each side, matching an existing camera as much as possible.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification; you may receive a nil return value depending on the order of notification delivery.

    Declaration

    Objective-C

    - (nonnull MGLMapCamera *)camera:(nonnull MGLMapCamera *)camera
                                                 fittingCoordinateBounds:(MGLCoordinateBounds)bounds
                                                             edgePadding:(UIEdgeInsets)insets;

    Swift

    func camera(_ camera: MGLMapCamera, fitting bounds: MGLCoordinateBounds, edgePadding insets: UIEdgeInsets) -> MGLMapCamera

    Parameters

    camera

    The camera that the return camera should adhere to. All values on this camera will be manipulated except for pitch and direction.

    bounds

    The coordinate bounds to fit to the receiver’s viewport.

    insets

    The minimum padding (in screen points) that would be visible around the returned camera object if it were set as the receiver’s camera.

    Return Value

    A camera object centered on the same location as the coordinate bounds with zoom level as high (close to the ground) as possible while still including the entire coordinate bounds. The initial camera’s pitch and direction will be honored.

  • -camera:fittingShape:edgePadding:

    Returns the camera that best fits the given shape with some additional padding on each side, matching an existing camera as much as possible.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification; you may receive a nil return value depending on the order of notification delivery.

    Declaration

    Objective-C

    - (nonnull MGLMapCamera *)camera:(nonnull MGLMapCamera *)camera
                                                            fittingShape:(nonnull MGLShape *)shape
                                                             edgePadding:(UIEdgeInsets)insets;

    Swift

    func camera(_ camera: MGLMapCamera, fitting shape: MGLShape, edgePadding insets: UIEdgeInsets) -> MGLMapCamera

    Parameters

    camera

    The camera that the return camera should adhere to. All values on this camera will be manipulated except for pitch and direction.

    shape

    The shape to fit to the receiver’s viewport.

    insets

    The minimum padding (in screen points) that would be visible around the returned camera object if it were set as the receiver’s camera.

    Return Value

    A camera object centered on the shape’s center with zoom level as high (close to the ground) as possible while still including the entire shape. The initial camera’s pitch and direction will be honored.

  • -cameraThatFitsShape:direction:edgePadding:

    Returns the camera that best fits the given shape with some additional padding on each side while looking in the specified direction.

    Note

    The behavior of this method is undefined if called in response to UIApplicationWillTerminateNotification; you may receive a nil return value depending on the order of notification delivery.

    Declaration

    Objective-C

    - (nonnull MGLMapCamera *)cameraThatFitsShape:(nonnull MGLShape *)shape
                                                                            direction:(CLLocationDirection)direction
                                                                          edgePadding:(UIEdgeInsets)insets;

    Swift

    func cameraThatFitsShape(_ shape: MGLShape, direction: CLLocationDirection, edgePadding insets: UIEdgeInsets) -> MGLMapCamera

    Parameters

    shape

    The shape to fit to the receiver’s viewport.

    direction

    The direction of the viewport, measured in degrees clockwise from true north.

    insets

    The minimum padding (in screen points) that would be visible around the returned camera object if it were set as the receiver’s camera.

    Return Value

    A camera object centered on the shape’s center with zoom level as high (close to the ground) as possible while still including the entire shape. The camera object uses the current pitch.

  • -anchorPointForGesture:

    Returns the point in this view’s coordinate system on which to “anchor” in response to a user-initiated gesture.

    For example, a pinch-to-zoom gesture would anchor the map at the midpoint of the pinch.

    If the userTrackingMode property is not MGLUserTrackingModeNone, the user annotation is used as the anchor point.

    Subclasses may override this method to provide specialized behavior - for example, anchoring on the map’s center point to provide a “locked” zooming mode.

    Declaration

    Objective-C

    - (CGPoint)anchorPointForGesture:(nonnull UIGestureRecognizer *)gesture;

    Swift

    func anchorPoint(forGesture gesture: UIGestureRecognizer) -> CGPoint

    Parameters

    gesture

    An anchorable user gesture.

    Return Value

    The point on which to anchor in response to the gesture.

  • contentInset

    The distance from the edges of the map view’s frame to the edges of the map view’s logical viewport.

    When the value of this property is equal to UIEdgeInsetsZero, viewport properties such as centerCoordinate assume a viewport that matches the map view’s frame. Otherwise, those properties are inset, excluding part of the frame from the viewport. For instance, if the only the top edge is inset, the map center is effectively shifted downward.

    When the map view’s superview is an instance of UIViewController whose automaticallyAdjustsScrollViewInsets property is YES, the value of this property may be overridden at any time.

    The usage of automaticallyAdjustsScrollViewInsets has been deprecated use the map view’s property MGLMapView.automaticallyAdjustsContentInsetinstead.

    Changing the value of this property updates the map view immediately. If you want to animate the change, use the -setContentInset:animated:completionHandler: method instead.

    Declaration

    Objective-C

    @property (nonatomic) UIEdgeInsets contentInset;

    Swift

    var contentInset: UIEdgeInsets { get set }
  • cameraEdgeInsets

    The current edge insets of the current map view’s camera.

    Camera edge insets are formed as accumulation of map view’s content insets and the edge padding passed to the method like seCamera:...edgePadding:, setVisibleCoordinates:...edgePadding:, showAnnotations:...edgePadding: etc.

    The camera edge insets influences the centerCoordinate of the viewport. This value is read-only, in order to apply paddings, use either persistent contentInset, either transient edgePadding parameter of the set... methods.

    Declaration

    Objective-C

    @property (nonatomic, readonly) UIEdgeInsets cameraEdgeInsets;

    Swift

    var cameraEdgeInsets: UIEdgeInsets { get }
  • -setContentInset:animated:

    Deprecated. Sets the distance from the edges of the map view’s frame to the edges of the map view’s logical viewport with an optional transition animation.

    When the value of this property is equal to UIEdgeInsetsZero, viewport properties such as centerCoordinate assume a viewport that matches the map view’s frame. Otherwise, those properties are inset, excluding part of the frame from the viewport. For instance, if the only the top edge is inset, the map center is effectively shifted downward.

    When the map view’s superview is an instance of UIViewController whose automaticallyAdjustsScrollViewInsets property is YES, the value of this property may be overridden at any time.

    The usage of automaticallyAdjustsScrollViewInsets has been deprecated use the map view’s property MGLMapView.automaticallyAdjustsContentInsetinstead.

    To specify a completion handler to execute after the animation finishes, use the -setContentInset:animated:completionHandler: method.

    Declaration

    Objective-C

    - (void)setContentInset:(UIEdgeInsets)contentInset animated:(BOOL)animated;

    Swift

    func setContentInset(_ contentInset: UIEdgeInsets, animated: Bool)

    Parameters

    contentInset

    The new values to inset the content by.

    animated

    Specify YES if you want the map view to animate the change to the content inset or NO if you want the map to inset the content immediately.

  • -setContentInset:animated:completionHandler:

    Sets the distance from the edges of the map view’s frame to the edges of the map view’s logical viewport with an optional transition animation and completion handler.

    When the value of this property is equal to UIEdgeInsetsZero, viewport properties such as centerCoordinate assume a viewport that matches the map view’s frame. Otherwise, those properties are inset, excluding part of the frame from the viewport. For instance, if the only the top edge is inset, the map center is effectively shifted downward.

    When the map view’s superview is an instance of UIViewController whose automaticallyAdjustsScrollViewInsets property is YES, the value of this property may be overridden at any time.

    The usage of automaticallyAdjustsScrollViewInsets has been deprecated use the map view’s property MGLMapView.automaticallyAdjustsContentInsetinstead.

    Declaration

    Objective-C

    - (void)setContentInset:(UIEdgeInsets)contentInset
                                                       animated:(BOOL)animated
                                              completionHandler:(nullable void (^)(void))completion;

    Swift

    func setContentInset(_ contentInset: UIEdgeInsets, animated: Bool) async

    Parameters

    contentInset

    The new values to inset the content by.

    animated

    Specify YES if you want the map view to animate the change to the content inset or NO if you want the map to inset the content immediately.

    completion

    The block executed after the animation finishes.

Converting Geographic Coordinates

  • -convertPoint:toCoordinateFromView:

    Converts a point in the given view’s coordinate system to a geographic coordinate.

    See the Point conversion example to learn how to convert a CGPoint to a map coordinate.

    Declaration

    Objective-C

    - (CLLocationCoordinate2D)convertPoint:(CGPoint)point
                                                          toCoordinateFromView:(nullable UIView *)view;

    Swift

    func convert(_ point: CGPoint, toCoordinateFrom view: UIView?) -> CLLocationCoordinate2D

    Parameters

    point

    The point to convert.

    view

    The view in whose coordinate system the point is expressed.

    Return Value

    The geographic coordinate at the given point.

  • -convertCoordinate:toPointToView:

    Converts a geographic coordinate to a point in the given view’s coordinate system.

    See the Point conversion example to learn how to convert a map coordinate to a CGPoint object.

    Declaration

    Objective-C

    - (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate
                                                       toPointToView:(nullable UIView *)view;

    Swift

    func convert(_ coordinate: CLLocationCoordinate2D, toPointTo view: UIView?) -> CGPoint

    Parameters

    coordinate

    The geographic coordinate to convert.

    view

    The view in whose coordinate system the returned point should be expressed. If this parameter is nil, the returned point is expressed in the window’s coordinate system. If view is not nil, it must belong to the same window as the map view.

    Return Value

    The point (in the appropriate view or window coordinate system) corresponding to the given geographic coordinate.

  • -convertRect:toCoordinateBoundsFromView:

    Converts a rectangle in the given view’s coordinate system to a geographic bounding box.

    If the returned coordinate bounds contains a longitude is less than −180 degrees or greater than 180 degrees, the bounding box straddles the antimeridian or international date line.

    Declaration

    Objective-C

    - (MGLCoordinateBounds)convertRect:(CGRect)rect
                                                toCoordinateBoundsFromView:(nullable UIView *)view;

    Swift

    func convert(_ rect: CGRect, toCoordinateBoundsFrom view: UIView?) -> MGLCoordinateBounds

    Parameters

    rect

    The rectangle to convert.

    view

    The view in whose coordinate system the rectangle is expressed.

    Return Value

    The geographic bounding box coextensive with the given rectangle.

  • -convertCoordinateBounds:toRectToView:

    Converts a geographic bounding box to a rectangle in the given view’s coordinate system.

    To bring both sides of the antimeridian or international date line into view, specify some longitudes less than −180 degrees or greater than 180 degrees. For example, to show both Tokyo and San Francisco simultaneously, you could set the visible bounds to extend from (35.68476, −220.24257) to (37.78428, −122.41310).

    Declaration

    Objective-C

    - (CGRect)convertCoordinateBounds:(MGLCoordinateBounds)bounds
                                                             toRectToView:(nullable UIView *)view;

    Swift

    func convert(_ bounds: MGLCoordinateBounds, toRectTo view: UIView?) -> CGRect

    Parameters

    bounds

    The geographic bounding box to convert.

    view

    The view in whose coordinate system the returned rectangle should be expressed. If this parameter is nil, the returned rectangle is expressed in the window’s coordinate system. If view is not nil, it must belong to the same window as the map view.

  • -metersPerPointAtLatitude:

    Returns the distance spanned by one point in the map view’s coordinate system at the given latitude and current zoom level.

    The distance between points decreases as the latitude approaches the poles. This relationship parallels the relationship between longitudinal coordinates at different latitudes.

    Declaration

    Objective-C

    - (CLLocationDistance)metersPerPointAtLatitude:(CLLocationDegrees)latitude;

    Swift

    func metersPerPoint(atLatitude latitude: CLLocationDegrees) -> CLLocationDistance

    Parameters

    latitude

    The latitude of the geographic coordinate represented by the point.

    Return Value

    The distance in meters spanned by a single point.

  • -mapProjection

    Returns the new map projection instance initialized with the map view, i.e. with the current camera state.

    Declaration

    Objective-C

    - (nonnull MGLMapProjection *)mapProjection;

    Swift

    func mapProjection() -> MGLMapProjection

Annotating the Map

  • annotations

    The complete list of annotations associated with the receiver. (read-only)

    The objects in this array must adopt the MGLAnnotation protocol. If no annotations are associated with the map view, the value of this property is nil.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nullable) NSArray<id<MGLAnnotation>> *annotations;
  • -addAnnotation:

    Adds an annotation to the map view.

    Note

    MGLMultiPolyline, MGLMultiPolygon, MGLShapeCollection, and MGLPointCollection objects cannot be added to the map view at this time. Any multipoint, multipolyline, multipolygon, shape or point collection object that is specified is silently ignored.

    See the Annotation models and Add a line annotation from GeoJSON examples to learn how to add an annotation to an MGLMapView object.

    Declaration

    Objective-C

    - (void)addAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Parameters

    annotation

    The annotation object to add to the receiver. This object must conform to the MGLAnnotation protocol. The map view retains the annotation object.

  • -addAnnotations:

    Adds an array of annotations to the map view.

    Note

    MGLMultiPolyline, MGLMultiPolygon, and MGLShapeCollection objects cannot be added to the map view at this time. Nor can MGLMultiPoint objects that are not instances of MGLPolyline or MGLPolygon. Any multipoint, multipolyline, multipolygon, or shape collection objects that are specified are silently ignored.

    Declaration

    Objective-C

    - (void)addAnnotations:(nonnull NSArray<id<MGLAnnotation>> *)annotations;

    Parameters

    annotations

    An array of annotation objects. Each object in the array must conform to the MGLAnnotation protocol. The map view retains each individual annotation object.

  • -removeAnnotation:

    Removes an annotation from the map view, deselecting it if it is selected.

    Removing an annotation object dissociates it from the map view entirely, preventing it from being displayed on the map. Thus you would typically call this method only when you want to hide or delete a given annotation.

    Declaration

    Objective-C

    - (void)removeAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Parameters

    annotation

    The annotation object to remove. This object must conform to the MGLAnnotation protocol

  • -removeAnnotations:

    Removes an array of annotations from the map view, deselecting any selected annotations in the array.

    Removing annotation objects dissociates them from the map view entirely, preventing them from being displayed on the map. Thus you would typically call this method only when you want to hide or delete the given annotations.

    Declaration

    Objective-C

    - (void)removeAnnotations:(nonnull NSArray<id<MGLAnnotation>> *)annotations;

    Parameters

    annotations

    The array of annotation objects to remove. Objects in the array must conform to the MGLAnnotation protocol.

  • -viewForAnnotation:

    Returns an MGLAnnotationView if the given annotation is currently associated with a view, otherwise nil.

    Declaration

    Objective-C

    - (nullable MGLAnnotationView *)viewForAnnotation:
                                            (nonnull id<MGLAnnotation>)annotation;

    Parameters

    annotation

    The annotation associated with the view. Annotation must conform to the MGLAnnotation protocol.

  • -dequeueReusableAnnotationImageWithIdentifier:

    Returns a reusable annotation image object associated with its identifier.

    For performance reasons, you should generally reuse MGLAnnotationImage objects for identical-looking annotations in your map views. Dequeueing saves time and memory during performance-critical operations such as scrolling.

    See the Add annotation views and images example learn how to most efficiently reuse an MGLAnnotationImage.

    Declaration

    Objective-C

    - (nullable __kindof MGLAnnotationImage *)
                                            dequeueReusableAnnotationImageWithIdentifier:(nonnull NSString *)identifier;

    Swift

    func dequeueReusableAnnotationImage(withIdentifier identifier: String) -> MGLAnnotationImage?

    Parameters

    identifier

    A string identifying the annotation image to be reused. This string is the same one you specify when initially returning the annotation image object using the -mapView:imageForAnnotation: method.

    Return Value

    An annotation image object with the given identifier, or nil if no such object exists in the reuse queue.

  • -dequeueReusableAnnotationViewWithIdentifier:

    Returns a reusable annotation view object associated with its identifier.

    For performance reasons, you should generally reuse MGLAnnotationView objects for identical-looking annotations in your map views. Dequeueing saves time and memory during performance-critical operations such as scrolling.

    Declaration

    Objective-C

    - (nullable __kindof MGLAnnotationView *)
                                            dequeueReusableAnnotationViewWithIdentifier:(nonnull NSString *)identifier;

    Swift

    func dequeueReusableAnnotationView(withIdentifier identifier: String) -> MGLAnnotationView?

    Parameters

    identifier

    A string identifying the annotation view to be reused. This string is the same one you specify when initially returning the annotation view object using the -mapView:viewForAnnotation: method.

    Return Value

    An annotation view object with the given identifier, or nil if no such object exists in the reuse queue.

  • visibleAnnotations

    The complete list of annotations associated with the receiver that are currently visible.

    The objects in this array must adopt the MGLAnnotation protocol. If no annotations are associated with the map view or if no annotations associated with the map view are currently visible, the value of this property is nil.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nullable) NSArray<id<MGLAnnotation>> *visibleAnnotations;
  • -visibleAnnotationsInRect:

    Returns the list of annotations associated with the receiver that intersect with the given rectangle.

    Declaration

    Objective-C

    - (nullable NSArray<id<MGLAnnotation>> *)visibleAnnotationsInRect:(CGRect)rect;

    Parameters

    rect

    A rectangle expressed in the map view’s coordinate system.

    Return Value

    An array of objects that adopt the MGLAnnotation protocol or nil if no annotations associated with the map view are currently visible in the rectangle.

Managing Annotation Selections

  • selectedAnnotations

    The currently selected annotations.

    Assigning a new array to this property selects only the first annotation in the array.

    If the annotation is of type MGLPointAnnotation and is offscreen, the camera will animate to bring the annotation and its callout just on screen. If you need finer control, consider using -selectAnnotation:animated:.

    Note

    In versions prior to 4.0.0 if the annotation was offscreen it was not selected.

    Declaration

    Objective-C

    @property (nonatomic, copy) NSArray<id<MGLAnnotation>> *_Nonnull selectedAnnotations;
  • -selectAnnotation:animated:

    Deprecated. Selects an annotation and displays its callout view.

    The animated parameter determines whether the selection is animated including whether the map is panned to bring the annotation into view, specifically:

    animated parameter Effect
    NO The annotation is selected, and the callout is presented. However the map is not panned to bring the annotation or callout into view. The presentation of the callout is NOT animated.
    YES The annotation is selected, and the callout is presented. If the annotation is not visible (or is partially visible) and is of type MGLPointAnnotation, the map is panned so that the annotation and its callout are brought into view. The annotation is not centered within the viewport.

    Note that a selection initiated by a single tap gesture is always animated.

    To specify a completion handler to execute after the animation finishes, use the -selectAnnotation:animated:completionHandler: method.

    Note

    In versions prior to 4.0.0 selecting an offscreen annotation did not change the camera.

    Declaration

    Objective-C

    - (void)selectAnnotation:(nonnull id<MGLAnnotation>)annotation
                                                        animated:(BOOL)animated;

    Parameters

    annotation

    The annotation object to select.

    animated

    If YES, the annotation and callout view are animated on-screen.

  • -selectAnnotation:animated:completionHandler:

    Selects an annotation and displays its callout view with an optional completion handler.

    The animated parameter determines whether the selection is animated including whether the map is panned to bring the annotation into view, specifically:

    animated parameter Effect
    NO The annotation is selected, and the callout is presented. However the map is not panned to bring the annotation or callout into view. The presentation of the callout is NOT animated.
    YES The annotation is selected, and the callout is presented. If the annotation is not visible (or is partially visible) and is of type MGLPointAnnotation, the map is panned so that the annotation and its callout are brought into view. The annotation is not centered within the viewport.

    Note that a selection initiated by a single tap gesture is always animated.

    Note

    In versions prior to 4.0.0 selecting an offscreen annotation did not change the camera.

    Declaration

    Objective-C

    - (void)selectAnnotation:(nonnull id<MGLAnnotation>)annotation
                                                        animated:(BOOL)animated
                                               completionHandler:(nullable void (^)(void))completion;

    Parameters

    annotation

    The annotation object to select.

    animated

    If YES, the annotation and callout view are animated on-screen.

    completion

    The block executed after the animation finishes.

  • -deselectAnnotation:animated:

    Deselects an annotation and hides its callout view.

    Declaration

    Objective-C

    - (void)deselectAnnotation:(nullable id<MGLAnnotation>)annotation
                                                          animated:(BOOL)animated;

    Parameters

    annotation

    The annotation object to deselect.

    animated

    If YES, the callout view is animated offscreen.

Overlaying the Map

  • overlays

    The complete list of overlays associated with the receiver. (read-only)

    The objects in this array must adopt the MGLOverlay protocol. If no overlays are associated with the map view, the value of this property is empty array.

    Declaration

    Objective-C

    @property (nonatomic, readonly, nonnull) NSArray<id<MGLOverlay>> *overlays;
  • -addOverlay:

    Adds a single overlay object to the map.

    To remove an overlay from a map, use the -removeOverlay: method.

    Declaration

    Objective-C

    - (void)addOverlay:(nonnull id<MGLOverlay>)overlay;

    Parameters

    overlay

    The overlay object to add. This object must conform to the MGLOverlay protocol.

  • -addOverlays:

    Adds an array of overlay objects to the map.

    To remove multiple overlays from a map, use the -removeOverlays: method.

    Declaration

    Objective-C

    - (void)addOverlays:(nonnull NSArray<id<MGLOverlay>> *)overlays;

    Parameters

    overlays

    An array of objects, each of which must conform to the MGLOverlay protocol.

  • -removeOverlay:

    Removes a single overlay object from the map.

    If the specified overlay is not currently associated with the map view, this method does nothing.

    Declaration

    Objective-C

    - (void)removeOverlay:(nonnull id<MGLOverlay>)overlay;

    Parameters

    overlay

    The overlay object to remove.

  • -removeOverlays:

    Removes one or more overlay objects from the map.

    If a given overlay object is not associated with the map view, it is ignored.

    Declaration

    Objective-C

    - (void)removeOverlays:(nonnull NSArray<id<MGLOverlay>> *)overlays;

    Parameters

    overlays

    An array of objects, each of which conforms to the MGLOverlay protocol.

Accessing the Underlying Map Data

  • -visibleFeaturesAtPoint:

    Returns an array of rendered map features that intersect with a given point.

    This method may return features from any of the map’s style layers. To restrict the search to a particular layer or layers, use the -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers: method. For more information about searching for map features, see that method’s documentation.

    See the Select a feature within a layer example to learn how to query an MGLMapView object for visible MGLFeature objects.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)visibleFeaturesAtPoint:(CGPoint)point;

    Parameters

    point

    A point expressed in the map view’s coordinate system.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

  • -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers:

    Returns an array of rendered map features that intersect with a given point, restricted to the given style layers.

    This method returns all the intersecting features from the specified layers. To filter the returned features, use the -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers:predicate: method. For more information about searching for map features, see that method’s documentation.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)visibleFeaturesAtPoint:(CGPoint)point
                                                                       inStyleLayersWithIdentifiers:
                                                                           (nullable NSSet<NSString *> *)
                                                                               styleLayerIdentifiers;

    Parameters

    point

    A point expressed in the map view’s coordinate system.

    styleLayerIdentifiers

    A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

  • -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers:predicate:

    Returns an array of rendered map features that intersect with a given point, restricted to the given style layers and filtered by the given predicate.

    Each object in the returned array represents a feature rendered by the current style and provides access to attributes specified by the relevant map content sources. The returned array includes features loaded by MGLShapeSource and MGLVectorTileSource objects but does not include anything from MGLRasterTileSource objects, or from video or canvas sources, which are unsupported by this SDK.

    The returned features are drawn by a style layer in the current style. For example, suppose the current style uses the Mapbox Streets source, but none of the specified style layers includes features that have the maki property set to bus. If you pass a point corresponding to the location of a bus stop into this method, the bus stop feature does not appear in the resulting array. On the other hand, if the style does include bus stops, an MGLFeature object representing that bus stop is returned and its featureAttributes dictionary has the maki key set to bus (along with other attributes). The dictionary contains only the attributes provided by the tile source; it does not include computed attribute values or rules about how the feature is rendered by the current style.

    The returned array is sorted by z-order, starting with the topmost rendered feature and ending with the bottommost rendered feature. A feature that is rendered multiple times due to wrapping across the antimeridian at low zoom levels is included only once, subject to the caveat that follows.

    Features come from tiled vector data or GeoJSON data that is converted to tiles internally, so feature geometries are clipped at tile boundaries and features may appear duplicated across tiles. For example, suppose the specified point lies along a road that spans the screen. The resulting array includes those parts of the road that lie within the map tile that contain the specified point, even if the road extends into other tiles.

    To find out the layer names in a particular style, view the style in Mapbox Studio.

    Only visible features are returned. To obtain features regardless of visibility, use the -[MGLVectorTileSource featuresInSourceLayersWithIdentifiers:predicate:] and -[MGLShapeSource featuresMatchingPredicate:] methods on the relevant sources.

    The returned features may also include features corresponding to annotations. These features are not object-equal to the MGLAnnotation objects that were originally added to the map. To query the map for annotations, use visibleAnnotations or -[MGLMapView visibleAnnotationsInRect:].

    Note

    Layer identifiers are not guaranteed to exist across styles or different versions of the same style. Applications that use this API must first set the style URL to an explicitly versioned style using a convenience method like +[MGLStyle outdoorsStyleURLWithVersion:], MGLMapView’s “Style URL” inspectable in Interface Builder, or a manually constructed NSURL. This approach also avoids layer identifer name changes that will occur in the default style’s layers over time.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)
                                                  visibleFeaturesAtPoint:(CGPoint)point
                                            inStyleLayersWithIdentifiers:
                                                (nullable NSSet<NSString *> *)styleLayerIdentifiers
                                                               predicate:(nullable NSPredicate *)predicate;

    Parameters

    point

    A point expressed in the map view’s coordinate system.

    styleLayerIdentifiers

    A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.

    predicate

    A predicate to filter the returned features.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

  • -visibleFeaturesInRect:

    Returns an array of rendered map features that intersect with the given rectangle.

    This method may return features from any of the map’s style layers. To restrict the search to a particular layer or layers, use the -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers: method. For more information about searching for map features, see that method’s documentation.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)visibleFeaturesInRect:(CGRect)rect;

    Parameters

    rect

    A rectangle expressed in the map view’s coordinate system.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

  • -visibleFeaturesInRect:inStyleLayersWithIdentifiers:

    Returns an array of rendered map features that intersect with the given rectangle, restricted to the given style layers.

    This method returns all the intersecting features from the specified layers. To filter the returned features, use the -visibleFeaturesAtPoint:inStyleLayersWithIdentifiers:predicate: method. For more information about searching for map features, see that method’s documentation.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)visibleFeaturesInRect:(CGRect)rect
                                                                      inStyleLayersWithIdentifiers:
                                                                          (nullable NSSet<NSString *> *)
                                                                              styleLayerIdentifiers;

    Parameters

    rect

    A rectangle expressed in the map view’s coordinate system.

    styleLayerIdentifiers

    A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

  • -visibleFeaturesInRect:inStyleLayersWithIdentifiers:predicate:

    Returns an array of rendered map features that intersect with the given rectangle, restricted to the given style layers and filtered by the given predicate.

    Each object in the returned array represents a feature rendered by the current style and provides access to attributes specified by the relevant map content sources. The returned array includes features loaded by MGLShapeSource and MGLVectorTileSource objects but does not include anything from MGLRasterTileSource objects, or from video or canvas sources, which are unsupported by this SDK.

    The returned features are drawn by a style layer in the current style. For example, suppose the current style uses the Mapbox Streets source, but none of the specified style layers includes features that have the maki property set to bus. If you pass a rectangle containing the location of a bus stop into this method, the bus stop feature does not appear in the resulting array. On the other hand, if the style does include bus stops, an MGLFeature object representing that bus stop is returned and its featureAttributes dictionary has the maki key set to bus (along with other attributes). The dictionary contains only the attributes provided by the tile source; it does not include computed attribute values or rules about how the feature is rendered by the current style.

    The returned array is sorted by z-order, starting with the topmost rendered feature and ending with the bottommost rendered feature. A feature that is rendered multiple times due to wrapping across the antimeridian at low zoom levels is included only once, subject to the caveat that follows.

    Features come from tiled vector data or GeoJSON data that is converted to tiles internally, so feature geometries are clipped at tile boundaries and features may appear duplicated across tiles. For example, suppose the specified rectangle intersects with a road that spans the screen. The resulting array includes those parts of the road that lie within the map tiles covering the specified rectangle, even if the road extends into other tiles. The portion of the road within each map tile is included individually.

    To find out the layer names in a particular style, view the style in Mapbox Studio.

    Only visible features are returned. To obtain features regardless of visibility, use the -[MGLVectorTileSource featuresInSourceLayersWithIdentifiers:predicate:] and -[MGLShapeSource featuresMatchingPredicate:] methods on the relevant sources.

    Note

    Layer identifiers are not guaranteed to exist across styles or different versions of the same style. Applications that use this API must first set the style URL to an explicitly versioned style using a convenience method like +[MGLStyle outdoorsStyleURLWithVersion:], MGLMapView’s “Style URL” inspectable in Interface Builder, or a manually constructed NSURL. This approach also avoids layer identifer name changes that will occur in the default style’s layers over time.

    Note

    Layer identifiers are not guaranteed to exist across styles or different versions of the same style. Applications that use this API must first set the style URL to an explicitly versioned style using a convenience method like +[MGLStyle outdoorsStyleURLWithVersion:], MGLMapView’s “Style URL” inspectable in Interface Builder, or a manually constructed NSURL. This approach also avoids layer identifer name changes that will occur in the default style’s layers over time.

    Declaration

    Objective-C

    - (nonnull NSArray<id<MGLFeature>> *)
                                                   visibleFeaturesInRect:(CGRect)rect
                                            inStyleLayersWithIdentifiers:
                                                (nullable NSSet<NSString *> *)styleLayerIdentifiers
                                                               predicate:(nullable NSPredicate *)predicate;

    Parameters

    rect

    A rectangle expressed in the map view’s coordinate system.

    styleLayerIdentifiers

    A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.

    predicate

    A predicate to filter the returned features.

    Return Value

    An array of objects conforming to the MGLFeature protocol that represent features in the sources used by the current style.

Debugging the Map

  • debugMask

    The options that determine which debugging aids are shown on the map.

    These options are all disabled by default and should remain disabled in released software for performance and aesthetic reasons.

    Declaration

    Objective-C

    @property (nonatomic) MGLMapDebugMaskOptions debugMask;

    Swift

    var debugMask: MGLMapDebugMaskOptions { get set }

MGLMapViewDelegate

@protocol MGLMapViewDelegate <NSObject>

The MGLMapViewDelegate protocol defines a set of optional methods that you can use to receive map-related update messages. Because many map operations require the MGLMapView class to load data asynchronously, the map view calls these methods to notify your application when specific operations complete. The map view also uses these methods to request information about annotations displayed on the map, such as the styles and interaction modes to apply to individual annotations.

Responding to Map Position Changes

  • -mapView:shouldChangeFromCamera:toCamera:

    Asks the delegate whether the map view should be allowed to change from the existing camera to the new camera in response to a user gesture.

    This method is called as soon as the user gesture is recognized. It is not called in response to a programmatic camera change, such as by setting the centerCoordinate property or calling -flyToCamera:completionHandler:.

    This method is called many times during gesturing, so you should avoid performing complex or performance-intensive tasks in your implementation.

    See the Restrict map panning to an area example to learn how to use this method and MGLMapCamera objects to restrict a users ability to pan your map.

    Declaration

    Objective-C

    - (BOOL)mapView:(nonnull MGLMapView *)mapView
                      shouldChangeFromCamera:(nonnull MGLMapCamera *)oldCamera
                                    toCamera:(nonnull MGLMapCamera *)newCamera;

    Swift

    optional func mapView(_ mapView: MGLMapView, shouldChangeFrom oldCamera: MGLMapCamera, to newCamera: MGLMapCamera) -> Bool

    Parameters

    mapView

    The map view that the user is manipulating.

    oldCamera

    The camera representing the viewpoint at the moment the gesture is recognized. If this method returns NO, the map view’s camera continues to be this camera.

    newCamera

    The expected camera after the gesture completes. If this method returns YES, this camera becomes the map view’s camera.

    Return Value

    A Boolean value indicating whether the map view should stay at oldCamera or change to newCamera.

  • -mapView:regionWillChangeAnimated:

    Tells the delegate that the viewpoint depicted by the map view is about to change.

    This method is called whenever the currently displayed map camera will start changing for any reason.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                      regionWillChangeAnimated:(BOOL)animated;

    Swift

    optional func mapView(_ mapView: MGLMapView, regionWillChangeAnimated animated: Bool)

    Parameters

    mapView

    The map view whose viewpoint will change.

    animated

    Whether the change will cause an animated effect on the map.

  • -mapViewRegionIsChanging:

    Tells the delegate that the viewpoint depicted by the map view is changing.

    This method is called as the currently displayed map camera changes as part of an animation, whether due to a user gesture or due to a call to a method such as -[MGLMapView setCamera:animated:]. This method can be called before -mapViewDidFinishLoadingMap: is called.

    During the animation, this method may be called many times to report updates to the viewpoint. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting performance.

    See the Cluster point data example to learn how to trigger an action whenever the map region changes.

    Declaration

    Objective-C

    - (void)mapViewRegionIsChanging:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewRegionIsChanging(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view whose viewpoint is changing.

  • -mapView:regionDidChangeAnimated:

    Tells the delegate that the viewpoint depicted by the map view has finished changing.

    This method is called whenever the currently displayed map camera has finished changing, after any calls to -mapViewRegionIsChanging: due to animation. Therefore, this method can be called before -mapViewDidFinishLoadingMap: is called.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                      regionDidChangeAnimated:(BOOL)animated;

    Swift

    optional func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool)

    Parameters

    mapView

    The map view whose viewpoint has changed.

    animated

    Whether the change caused an animated effect on the map.

Loading the Map

  • -mapViewWillStartLoadingMap:

    Tells the delegate that the map view will begin to load.

    This method is called whenever the map view starts loading, including when a new style has been set and the map must reload.

    Declaration

    Objective-C

    - (void)mapViewWillStartLoadingMap:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewWillStartLoadingMap(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that is starting to load.

  • -mapViewDidFinishLoadingMap:

    Tells the delegate that the map view has finished loading.

    This method is called whenever the map view finishes loading, either after the initial load or after a style change has forced a reload.

    Declaration

    Objective-C

    - (void)mapViewDidFinishLoadingMap:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewDidFinishLoadingMap(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that has finished loading.

  • -mapViewDidFailLoadingMap:withError:

    Tells the delegate that the map view was unable to load data needed for displaying the map.

    This method may be called for a variety of reasons, including a network connection failure or a failure to fetch the style from the server. You can use the given error message to notify the user that map data is unavailable.

    Declaration

    Objective-C

    - (void)mapViewDidFailLoadingMap:(nonnull MGLMapView *)mapView
                                         withError:(nonnull NSError *)error;

    Swift

    optional func mapViewDidFailLoadingMap(_ mapView: MGLMapView, withError error: Error)

    Parameters

    mapView

    The map view that is unable to load the data.

    error

    The reason the data could not be loaded.

  • -mapViewWillStartRenderingFrame:

    Tells the delegate that the map view is about to redraw.

    This method is called any time the map view needs to redraw due to a change in the viewpoint or style property transition. This method may be called very frequently, even moreso than -mapViewRegionIsChanging:. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting performance.

    Declaration

    Objective-C

    - (void)mapViewWillStartRenderingFrame:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewWillStartRenderingFrame(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that is about to redraw.

  • -mapViewDidFinishRenderingFrame:fullyRendered:

    Tells the delegate that the map view has just redrawn.

    This method is called any time the map view needs to redraw due to a change in the viewpoint or style property transition. This method may be called very frequently, even moreso than -mapViewRegionIsChanging:. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting performance.

    Declaration

    Objective-C

    - (void)mapViewDidFinishRenderingFrame:(nonnull MGLMapView *)mapView
                                           fullyRendered:(BOOL)fullyRendered;

    Swift

    optional func mapViewDidFinishRenderingFrame(_ mapView: MGLMapView, fullyRendered: Bool)

    Parameters

    mapView

    The map view that has just redrawn.

  • -mapViewDidBecomeIdle:

    Tells the delegate that the map view is entering an idle state, and no more drawing will be necessary until new data is loaded or there is some interaction with the map.

    • No camera transitions are in progress
    • All currently requested tiles have loaded
    • All fade/transition animations have completed

    Declaration

    Objective-C

    - (void)mapViewDidBecomeIdle:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewDidBecomeIdle(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that has just entered the idle state.

  • -mapView:didFinishLoadingStyle:

    Tells the delegate that the map has just finished loading a style.

    This method is called during the initialization of the map view and after any subsequent loading of a new style. This method is called between the -mapViewWillStartRenderingMap: and -mapViewDidFinishRenderingMap: delegate methods. Changes to sources or layers of the current style do not cause this method to be called.

    This method is the earliest opportunity to modify the layout or appearance of the current style before the map view is displayed to the user.

    See the Dynamically style interactive points and Add multiple shapes from a single shape source examples to learn how to ensure a map’s style has loaded before modifying it at runtime.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                      didFinishLoadingStyle:(nonnull MGLStyle *)style;

    Swift

    optional func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle)

    Parameters

    mapView

    The map view that has just loaded a style.

    style

    The style that was loaded.

  • -mapView:shouldRemoveStyleImage:

    Asks the delegate whether the map view should evict cached images.

    This method is called in two scenarios: when the cumulative size of unused images exceeds the cache size or when the last tile that includes the image is removed from memory.

    Declaration

    Objective-C

    - (BOOL)mapView:(nonnull MGLMapView *)mapView
                      shouldRemoveStyleImage:(nonnull NSString *)imageName;

    Swift

    optional func mapView(_ mapView: MGLMapView, shouldRemoveStyleImage imageName: String) -> Bool

    Parameters

    mapView

    The map view that is evicting the image.

    imageName

    The image name that is going to be removed.

    Return Value

    A Boolean value indicating whether the map view should evict the cached image.

Tracking User Location

  • -mapViewWillStartLocatingUser:

    Tells the delegate that the map view will begin tracking the user’s location.

    This method is called when the value of the showsUserLocation property changes to YES.

    Declaration

    Objective-C

    - (void)mapViewWillStartLocatingUser:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewWillStartLocatingUser(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that is tracking the user’s location.

  • -mapViewDidStopLocatingUser:

    Tells the delegate that the map view has stopped tracking the user’s location.

    This method is called when the value of the showsUserLocation property changes to NO.

    Declaration

    Objective-C

    - (void)mapViewDidStopLocatingUser:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewDidStopLocatingUser(_ mapView: MGLMapView)

    Parameters

    mapView

    The map view that is tracking the user’s location.

  • -mapViewStyleForDefaultUserLocationAnnotationView:

    Asks the delegate styling options for each default user location annotation view.

    This method is called many times during gesturing, so you should avoid performing complex or performance-intensive tasks in your implementation.

    Declaration

    Objective-C

    - (nonnull MGLUserLocationAnnotationViewStyle *)
                      mapViewStyleForDefaultUserLocationAnnotationView:
                          (nonnull MGLMapView *)mapView;

    Swift

    optional func mapView(styleForDefaultUserLocationAnnotationView mapView: MGLMapView) -> MGLUserLocationAnnotationViewStyle

    Parameters

    mapView

    The map view that is tracking the user’s location.

  • -mapView:didUpdateUserLocation:

    Tells the delegate that the location of the user was updated.

    While the showsUserLocation property is set to YES, this method is called whenever a new location update is received by the map view. This method is also called if the map view’s user tracking mode is set to MGLUserTrackingModeFollowWithHeading and the heading changes, or if it is set to MGLUserTrackingModeFollowWithCourse and the course changes.

    This method is not called if the application is currently running in the background. If you want to receive location updates while running in the background, you must use the Core Location framework.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                      didUpdateUserLocation:(nullable MGLUserLocation *)userLocation;

    Swift

    optional func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?)

    Parameters

    mapView

    The map view that is tracking the user’s location.

    userLocation

    The location object representing the user’s latest location. This property may be nil.

  • -mapView:didFailToLocateUserWithError:

    Tells the delegate that an attempt to locate the user’s position failed.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                      didFailToLocateUserWithError:(nonnull NSError *)error;

    Swift

    optional func mapView(_ mapView: MGLMapView, didFailToLocateUserWithError error: Error)

    Parameters

    mapView

    The map view that is tracking the user’s location.

    error

    An error object containing the reason why location tracking failed.

  • -mapView:didChangeUserTrackingMode:animated:

    Tells the delegate that the map view’s user tracking mode has changed.

    This method is called after the map view asynchronously changes to reflect the new user tracking mode, for example by beginning to zoom or rotate.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didChangeUserTrackingMode:(MGLUserTrackingMode)mode
                                       animated:(BOOL)animated;

    Swift

    optional func mapView(_ mapView: MGLMapView, didChange mode: MGLUserTrackingMode, animated: Bool)

    Parameters

    mapView

    The map view that changed its tracking mode.

    mode

    The new tracking mode.

    animated

    Whether the change caused an animated effect on the map.

  • -mapViewUserLocationAnchorPoint:

    Returns a screen coordinate at which to position the user location annotation. This coordinate is relative to the map view’s origin after applying the map view’s content insets.

    When unimplemented, the user location annotation is aligned within the center of the map view with respect to the content insets.

    This method will override any values set by MGLMapView.userLocationVerticalAlignment or -[MGLMapView setUserLocationVerticalAlignment:animated:].

    Declaration

    Objective-C

    - (CGPoint)mapViewUserLocationAnchorPoint:(nonnull MGLMapView *)mapView;

    Swift

    optional func mapViewUserLocationAnchorPoint(_ mapView: MGLMapView) -> CGPoint

    Parameters

    mapView

    The map view that is tracking the user’s location.

  • -mapView:didChangeLocationManagerAuthorization:

    Tells the delegate that the map’s location updates accuracy authorization has changed.

    This method is called after the user changes location accuracy authorization when requesting location permissions or in privacy settings.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didChangeLocationManagerAuthorization:
                          (nonnull id<MGLLocationManager>)manager;

    Swift

    optional func mapView(_ mapView: MGLMapView, didChangeLocationManagerAuthorization manager: MGLLocationManager)

    Parameters

    mapView

    The map view that changed its location accuracy authorization.

    manager

    The location manager reporting the update.

Managing the Appearance of Annotations

  • -mapView:imageForAnnotation:

    Returns an annotation image object to mark the given point annotation object on the map.

    Implement this method to mark a point annotation with a static image. If you want to mark a particular point annotation with an annotation view instead, omit this method or have it return nil for that annotation, then implement -mapView:viewForAnnotation:.

    Static annotation images use less memory and draw more quickly than annotation views. On the other hand, annotation views are compatible with UIKit, Core Animation, and other Cocoa Touch frameworks.

    See the Annotation models, Add annotation views and images, and Mark a place on the map with an image examples to learn to specify which image should be used for MGLAnnotation objects that have been added to your map.

    Declaration

    Objective-C

    - (nullable MGLAnnotationImage *)mapView:(nonnull MGLMapView *)mapView
                                        imageForAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage?

    Parameters

    mapView

    The map view that requested the annotation image.

    annotation

    The object representing the annotation that is about to be displayed.

    Return Value

    The annotation image object to display for the given annotation or nil if you want to display the default marker image or an annotation view.

  • -mapView:alphaForShapeAnnotation:

    Returns the alpha value to use when rendering a shape annotation.

    A value of 0.0 results in a completely transparent shape. A value of 1.0, the default, results in a completely opaque shape.

    This method sets the opacity of an entire shape, inclusive of its stroke and fill. To independently set the values for stroke or fill, specify an alpha component in the color returned by -mapView:strokeColorForShapeAnnotation: or -mapView:fillColorForPolygonAnnotation:.

    Declaration

    Objective-C

    - (CGFloat)mapView:(nonnull MGLMapView *)mapView
                         alphaForShapeAnnotation:(nonnull MGLShape *)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat

    Parameters

    mapView

    The map view rendering the shape annotation.

    annotation

    The annotation being rendered.

    Return Value

    An alpha value between 0 and 1.0.

  • -mapView:strokeColorForShapeAnnotation:

    Returns the color to use when rendering the outline of a shape annotation.

    The default stroke color is the map view’s tint color. If a pattern color is specified, the result is undefined.

    Opacity may be set by specifying an alpha component. The default alpha value is 1.0 and results in a completely opaque stroke.

    See the Annotation models example to learn how to modify the outline color of an MGLShape object that has been added to your map as an annotation.

    Declaration

    Objective-C

    - (nonnull UIColor *)mapView:(nonnull MGLMapView *)mapView
                         strokeColorForShapeAnnotation:(nonnull MGLShape *)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor

    Parameters

    mapView

    The map view rendering the shape annotation.

    annotation

    The annotation being rendered.

    Return Value

    A color to use for the shape outline.

  • -mapView:fillColorForPolygonAnnotation:

    Returns the color to use when rendering the fill of a polygon annotation.

    The default fill color is the map view’s tint color. If a pattern color is specified, the result is undefined.

    Opacity may be set by specifying an alpha component. The default alpha value is 1.0 and results in a completely opaque shape.

    See the Add a polygon annotation example to learn how to modify the color of a an MGLPolygon at runtime.

    Declaration

    Objective-C

    - (nonnull UIColor *)mapView:(nonnull MGLMapView *)mapView
                         fillColorForPolygonAnnotation:(nonnull MGLPolygon *)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, fillColorForPolygonAnnotation annotation: MGLPolygon) -> UIColor

    Parameters

    mapView

    The map view rendering the polygon annotation.

    annotation

    The annotation being rendered.

    Return Value

    The polygon’s interior fill color.

  • -mapView:lineWidthForPolylineAnnotation:

    Returns the line width in points to use when rendering the outline of a polyline annotation.

    By default, the polyline is outlined with a line 3.0 points wide.

    See the Add a line annotation from GeoJSON example to learn how to modify the line width of an MGLPolylineFeature on your map.

    Declaration

    Objective-C

    - (CGFloat)mapView:(nonnull MGLMapView *)mapView
                         lineWidthForPolylineAnnotation:(nonnull MGLPolyline *)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat

    Parameters

    mapView

    The map view rendering the polygon annotation.

    annotation

    The annotation being rendered.

    Return Value

    A line width for the polyline, measured in points.

Managing Annotation Views

  • -mapView:viewForAnnotation:

    Returns a view object to mark the given point annotation object on the map.

    Implement this method to mark a point annotation with a view object. If you want to mark a particular point annotation with a static image instead, omit this method or have it return nil for that annotation, then implement -mapView:imageForAnnotation: instead.

    Annotation views are compatible with UIKit, Core Animation, and other Cocoa Touch frameworks. On the other hand, static annotation images use less memory and draw more quickly than annotation views.

    The user location annotation view can also be customized via this method. When annotation is an instance of MGLUserLocation (or equal to the map view’s userLocation property), return an instance of MGLUserLocationAnnotationView (or a subclass thereof).

    See the Add annotation views and images example to learn how to specify what MGLViewAnnotation to use for a given MGLPointAnnotation object on your map.

    Declaration

    Objective-C

    - (nullable MGLAnnotationView *)mapView:(nonnull MGLMapView *)mapView
                                        viewForAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView?

    Parameters

    mapView

    The map view that requested the annotation view.

    annotation

    The object representing the annotation that is about to be displayed.

    Return Value

    The view object to display for the given annotation or nil if you want to display an annotation image instead.

  • -mapView:didAddAnnotationViews:

    Tells the delegate that one or more annotation views have been added and positioned on the map.

    This method is called just after the views are added to the map. You can implement this method to animate the addition of the annotation views.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didAddAnnotationViews:
                          (nonnull NSArray<MGLAnnotationView *> *)annotationViews;

    Swift

    optional func mapView(_ mapView: MGLMapView, didAdd annotationViews: [MGLAnnotationView])

    Parameters

    mapView

    The map view to which the annotation views were added.

    annotationViews

    An array of MGLAnnotationView objects representing the views that were added.

Selecting Annotations

  • -mapView:shapeAnnotationIsEnabled:

    Returns a Boolean value indicating whether the shape annotation can be selected.

    If the return value is YES, the user can select the annotation by tapping on it. If the delegate does not implement this method, the default value is YES.

    Declaration

    Objective-C

    - (BOOL)mapView:(nonnull MGLMapView *)mapView
                         shapeAnnotationIsEnabled:(nonnull MGLShape *)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, shapeAnnotationIsEnabled annotation: MGLShape) -> Bool

    Parameters

    mapView

    The map view that has selected the annotation.

    annotation

    The object representing the shape annotation.

    Return Value

    A Boolean value indicating whether the annotation can be selected.

  • -mapView:didSelectAnnotation:

    Tells the delegate that one of its annotations was selected.

    You can use this method to track changes in the selection state of annotations.

    If the annotation is associated with an annotation view, you can also implement -mapView:didSelectAnnotationView:, which is called immediately after this method is called.

    See the Dynamically style interactive points example to learn how to remove an annotation view if it has already been selected.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didSelectAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation)

    Parameters

    mapView

    The map view containing the annotation.

    annotation

    The annotation that was selected.

  • -mapView:didDeselectAnnotation:

    Tells the delegate that one of its annotations was deselected.

    You can use this method to track changes in the selection state of annotations.

    If the annotation is associated with an annotation view, you can also implement -mapView:didDeselectAnnotationView:, which is called immediately after this method is called.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didDeselectAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, didDeselect annotation: MGLAnnotation)

    Parameters

    mapView

    The map view containing the annotation.

    annotation

    The annotation that was deselected.

  • Tells the delegate that one of its annotation views was selected.

    You can use this method to track changes in the selection state of annotation views.

    This method is only called for annotation views. To track changes in the selection state of all annotations, including those associated with static annotation images, implement -mapView:didSelectAnnotation:, which is called immediately before this method is called.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didSelectAnnotationView:(nonnull MGLAnnotationView *)annotationView;

    Swift

    optional func mapView(_ mapView: MGLMapView, didSelect annotationView: MGLAnnotationView)

    Parameters

    mapView

    The map view containing the annotation.

    annotationView

    The annotation view that was selected.

  • -mapView:didDeselectAnnotationView:

    Tells the delegate that one of its annotation views was deselected.

    You can use this method to track changes in the selection state of annotation views.

    This method is only called for annotation views. To track changes in the selection state of all annotations, including those associated with static annotation images, implement -mapView:didDeselectAnnotation:, which is called immediately before this method is called.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                         didDeselectAnnotationView:(nonnull MGLAnnotationView *)annotationView;

    Swift

    optional func mapView(_ mapView: MGLMapView, didDeselect annotationView: MGLAnnotationView)

    Parameters

    mapView

    The map view containing the annotation.

    annotationView

    The annotation view that was deselected.

Managing Callout Views

  • -mapView:annotationCanShowCallout:

    Returns a Boolean value indicating whether the annotation is able to display extra information in a callout bubble.

    This method is called after an annotation is selected, before any callout is displayed for the annotation.

    If the return value is YES, a callout view is shown when the user taps on an annotation, selecting it. The default callout displays the annotation’s title and subtitle. You can add accessory views to either end of the callout by implementing the -mapView:leftCalloutAccessoryViewForAnnotation: and -mapView:rightCalloutAccessoryViewForAnnotation: methods. You can further customize the callout’s contents by implementing the -mapView:calloutViewForAnnotation: method.

    If the return value is NO, or if this method is absent from the delegate, or if the annotation lacks a title, the annotation will not show a callout even when selected.

    See the Add annotation views and images, Display custom views as callouts, and Default callout usage examples to learn how to show callouts for MGLAnnotation objects.

    Declaration

    Objective-C

    - (BOOL)mapView:(nonnull MGLMapView *)mapView
                         annotationCanShowCallout:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool

    Parameters

    mapView

    The map view that has selected the annotation.

    annotation

    The object representing the annotation.

    Return Value

    A Boolean value indicating whether the annotation should show a callout.

  • -mapView:calloutViewForAnnotation:

    Returns a callout view to display for the given annotation.

    If this method is present in the delegate, it must return a new instance of a view dedicated to display the callout. The returned view will be configured by the map view.

    If this method is absent from the delegate, or if it returns nil, a standard, two-line, bubble-like callout view is displayed by default.

    See the Display custom views as callouts example to learn how to customize an MGLAnnotation object’s MGLCalloutView.

    Declaration

    Objective-C

    - (nullable id<MGLCalloutView>)mapView:(nonnull MGLMapView *)mapView
                                calloutViewForAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView?

    Parameters

    mapView

    The map view that requested the callout view.

    annotation

    The object representing the annotation.

    Return Value

    A view conforming to the MGLCalloutView protocol, or nil to use the default callout view.

  • -mapView:leftCalloutAccessoryViewForAnnotation:

    Returns the view to display on the left side of the standard callout bubble.

    The left callout view is typically used to convey information about the annotation or to link to custom information provided by your application.

    If the view you specify is a descendant of the UIControl class, you can use the map view’s delegate to receive notifications when your control is tapped, by implementing the -mapView:annotation:calloutAccessoryControlTapped: method. If the view you specify does not descend from UIControl, your view is responsible for handling any touch events within its bounds.

    If this method is absent from the delegate, or if it returns nil, the standard callout view has no accessory view on its left side. The return value of this method is ignored if -mapView:calloutViewForAnnotation: is present in the delegate.

    To display a view on the callout’s right side, implement the -mapView:rightCalloutAccessoryViewForAnnotation: method.

    See the Default callout usage example to learn how to modify the view that is displayed on the left side of the standard callout bubble.

    Declaration

    Objective-C

    - (nullable UIView *)mapView:(nonnull MGLMapView *)mapView
                         leftCalloutAccessoryViewForAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView?

    Parameters

    mapView

    The map view presenting the annotation callout.

    annotation

    The object representing the annotation with the callout.

    Return Value

    The accessory view to display.

  • -mapView:rightCalloutAccessoryViewForAnnotation:

    Returns the view to display on the right side of the standard callout bubble.

    The right callout view is typically used to convey information about the annotation or to link to custom information provided by your application.

    If the view you specify is a descendant of the UIControl class, you can use the map view’s delegate to receive notifications when your control is tapped, by implementing the -mapView:annotation:calloutAccessoryControlTapped: method. If the view you specify does not descend from UIControl, your view is responsible for handling any touch events within its bounds.

    If this method is absent from the delegate, or if it returns nil, the standard callout view has no accessory view on its right side. The return value of this method is ignored if -mapView:calloutViewForAnnotation: is present in the delegate.

    To display a view on the callout’s left side, implement the -mapView:leftCalloutAccessoryViewForAnnotation: method.

    See the Default callout usage example to learn how to modify the view that is displayed on the right side of the standard callout bubble.

    Declaration

    Objective-C

    - (nullable UIView *)mapView:(nonnull MGLMapView *)mapView
                         rightCalloutAccessoryViewForAnnotation:
                          (nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView?

    Parameters

    mapView

    The map view presenting the annotation callout.

    annotation

    The object representing the annotation with the callout.

    Return Value

    The accessory view to display.

  • -mapView:annotation:calloutAccessoryControlTapped:

    Tells the delegate that the user tapped one of the accessory controls in the annotation’s callout view.

    In a standard callout view, accessory views contain custom content and are positioned on either side of the annotation title text. If an accessory view you specify is a descendant of the UIControl class, the map view calls this method as a convenience whenever the user taps your view. You can use this method to respond to taps and perform any actions associated with that control. For example, if your control displays additional information about the annotation, you could use this method to present a modal panel with that information.

    If your custom accessory views are not descendants of the UIControl class, the map view does not call this method. If the annotation has a custom callout view via the -mapView:calloutViewForAnnotation: method, you can specify the custom accessory views using the MGLCalloutView protocol’s leftAccessoryView and rightAccessoryView properties.

    See the Default callout usage example to learn how to trigger an action when the standard callout bubble’s accessory control is tapped.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                                         annotation:(nonnull id<MGLAnnotation>)annotation
                         calloutAccessoryControlTapped:(nonnull UIControl *)control;

    Swift

    optional func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl)

    Parameters

    mapView

    The map view containing the specified annotation.

    annotation

    The annotation whose accessory view was tapped.

    control

    The control that was tapped.

  • -mapView:tapOnCalloutForAnnotation:

    Tells the delegate that the user tapped on an annotation’s callout view.

    This method is called when the user taps on the body of the callout view, as opposed to the callout’s left or right accessory view. If the annotation has a custom callout view via the -mapView:calloutViewForAnnotation: method, this method is only called whenever the callout view calls its delegate’s -[MGLCalloutViewDelegate calloutViewTapped:] method.

    If this method is present on the delegate, the standard callout view’s body momentarily highlights when the user taps it, whether or not this method does anything in response to the tap.

    See the Display custom views as callouts example to learn how to trigger an action when an MGLAnnotations MGLCalloutView is tapped.

    Declaration

    Objective-C

    - (void)mapView:(nonnull MGLMapView *)mapView
                            tapOnCalloutForAnnotation:(nonnull id<MGLAnnotation>)annotation;

    Swift

    optional func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation)

    Parameters

    mapView

    The map view containing the specified annotation.

    annotation

    The annotation whose callout was tapped.

MGLMapSnapshot


              @interface MGLMapSnapshot : NSObject

An image generated by a snapshotter object.

  • -pointForCoordinate:

    Converts the specified map coordinate to a point in the coordinate space of the image.

    Declaration

    Objective-C

    - (CGPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate;

    Swift

    func point(for coordinate: CLLocationCoordinate2D) -> CGPoint
  • -coordinateForPoint:

    Converts the specified image point to a map coordinate.

    Declaration

    Objective-C

    - (CLLocationCoordinate2D)coordinateForPoint:(CGPoint)point;

    Swift

    func coordinate(for point: CGPoint) -> CLLocationCoordinate2D
  • image

    The image of the map’s content.

    Declaration

    Objective-C

    @property (nonatomic, readonly) UIImage *_Nonnull image;

    Swift

    var image: UIImage { get }

MGLMapSnapshotOptions


                        @interface MGLMapSnapshotOptions : NSObject <NSCopying>

The options to use when creating images with the MGLMapSnapshotter.

  • -initWithStyleURL:camera:size:

    Creates a set of options with the minimum required information.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithStyleURL:(nullable NSURL *)styleURL
                                                      camera:(nonnull MGLMapCamera *)camera
                                                        size:(CGSize)size;

    Swift

    init(styleURL: URL?, camera: MGLMapCamera, size: CGSize)

    Parameters

    styleURL

    URL of the map style to snapshot. The URL may be a full HTTP, HTTPS URL, canonical URL or a path to a local file relative to the application’s resource path. Specify nil for the default style.

    size

    The image size.

Configuring the Map

  • styleURL

    URL of the map style to snapshot.

    Declaration

    Objective-C

    @property (nonatomic, readonly) NSURL *_Nonnull styleURL;

    Swift

    var styleURL: URL { get }
  • zoomLevel

    The zoom level.

    The default zoom level is 0. If this property is non-zero and the camera property is non-nil, the camera’s altitude is ignored in favor of this property’s value.

    Declaration

    Objective-C

    @property (nonatomic) double zoomLevel;

    Swift

    var zoomLevel: Double { get set }
  • camera

    A camera representing the viewport visible in the snapshot.

    If this property is non-nil and the coordinateBounds property is set to a non-empty coordinate bounds, the camera’s center coordinate and altitude are ignored in favor of the coordinateBounds property.

    Declaration

    Objective-C

    @property (nonatomic) MGLMapCamera *_Nonnull camera;

    Swift

    var camera: MGLMapCamera { get set }
  • coordinateBounds

    The coordinate rectangle that encompasses the bounds to capture.

    If this property is non-empty and the camera property is non-nil, the camera’s center coordinate and altitude are ignored in favor of this property’s value.

    Declaration

    Objective-C

    @property (nonatomic) MGLCoordinateBounds coordinateBounds;

    Swift

    var coordinateBounds: MGLCoordinateBounds { get set }

Configuring the Image

  • size

    The size of the output image, measured in points.

    Declaration

    Objective-C

    @property (nonatomic, readonly) CGSize size;

    Swift

    var size: CGSize { get }
  • scale

    The scale of the output image. Defaults to the main screen scale.

    The minimum scale is 1.

    Declaration

    Objective-C

    @property (nonatomic) CGFloat scale;

    Swift

    var scale: CGFloat { get set }

MGLMapSnapshotter


                                @interface MGLMapSnapshotter : NSObject <MGLStylable>

An MGLMapSnapshotter generates static raster images of the map. Each snapshot image depicts a portion of a map defined by an MGLMapSnapshotOptions object you provide. The snapshotter generates an MGLMapSnapshot object asynchronously, calling MGLMapSnapshotterDelegate methods if defined, then passing it into a completion handler once tiles and other resources needed for the snapshot are finished loading.

You can change the snapshotter’s options at any time and reuse the snapshotter for multiple distinct snapshots; however, the snapshotter can only generate one snapshot at a time. If you need to generate multiple snapshots concurrently, create multiple snapshotter objects.

For an interactive map, use the MGLMapView class. Both MGLMapSnapshotter and MGLMapView are compatible with offline packs managed by the MGLOfflineStorage class.

From a snapshot, you can obtain an image and convert geographic coordinates to the image’s coordinate space in order to superimpose markers and overlays. If you do not need offline map functionality, you can use the Snapshot class in MapboxStatic.swift to generate static map images with overlays.

Example

let camera = MGLMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 37.7184, longitude: -122.4365), altitude: 100, pitch: 20, heading: 0)
                                
                                let options = MGLMapSnapshotOptions(styleURL: MGLStyle.satelliteStreetsStyleURL, camera: camera, size: CGSize(width: 320, height: 480))
                                options.zoomLevel = 10
                                
                                let snapshotter = MGLMapSnapshotter(options: options)
                                snapshotter.start { (snapshot, error) in
                                    if let error = error {
                                        fatalError(error.localizedDescription)
                                    }
                                
                                    image = snapshot?.image
                                }
                                

See the Create a static map snapshot example to learn how to use the MGLMapSnapshotter to generate a static image based on an MGLMapView object’s style, camera, and view bounds.

MGLUserTrackingMode

enum MGLUserTrackingMode : NSUInteger {}

The mode used to track the user location on the map. Used with MGLMapView.userTrackingMode.

See the Switch between user tracking modes example to learn how to toggle modes and how each mode behaves.

  • MGLUserTrackingModeNone

    The map does not follow the user location.

    Declaration

    Objective-C

    MGLUserTrackingModeNone = 0

    Swift

    case none = 0
  • MGLUserTrackingModeFollow

    The map follows the user location. This tracking mode falls back to MGLUserTrackingModeNone if the user pans the map view.

    Declaration

    Objective-C

    MGLUserTrackingModeFollow

    Swift

    case follow = 1
  • MGLUserTrackingModeFollowWithHeading

    The map follows the user location and rotates when the heading changes. The default user location annotation displays a fan-shaped indicator with the current heading. The heading indicator represents the direction the device is facing, which is sized according to the reported accuracy.

    This tracking mode is disabled if the user pans the map view, but remains enabled if the user zooms in. If the user rotates the map view, this tracking mode will fall back to MGLUserTrackingModeFollow.

    Declaration

    Objective-C

    MGLUserTrackingModeFollowWithHeading

    Swift

    case followWithHeading = 2
  • MGLUserTrackingModeFollowWithCourse

    The map follows the user location and rotates when the course changes. Course represents the direction in which the device is traveling. The default user location annotation shows a puck-shaped indicator that rotates as the course changes.

    This tracking mode is disabled if the user pans the map view, but remains enabled if the user zooms in. If the user rotates the map view, this tracking mode will fall back to MGLUserTrackingModeFollow.

    Declaration

    Objective-C

    MGLUserTrackingModeFollowWithCourse

    Swift

    case followWithCourse = 3