MapboxMap
public final class MapboxMap : MapboxMapProtocol
extension MapboxMap: MapEventsObservable
MapboxMap provides access to the map model, including the camera, style, observable map events,
and querying rendered features. Obtain the MapboxMap instance for a MapView via MapView.mapboxMap.
Important
MapboxMap should only be used from the main thread.-
Triggers a repaint of the map. Calling this method is typically unnecessary but may be needed if using a custom layer that needs to be redrawn independently of other map changes.
Declaration
Swift
public func triggerRepaint()
-
Loads a
stylefrom a StyleURI, calling a completion closure when the style is fully loaded or there has been an error during load.Declaration
Parameters
styleURIStyleURI to load
completionClosure called when the style has been fully loaded. The
Resulttype encapsulates theStyleor error that occurred. SeeMapLoadingError -
Loads a
stylefrom a JSON string, calling a completion closure when the style is fully loaded or there has been an error during load.Declaration
Swift
public func loadStyleJSON(_ JSON: String, completion: ((Result<Style, Error>) -> Void)? = nil)Parameters
styleURIStyle JSON string
completionClosure called when the style has been fully loaded. The
Resulttype encapsulates theStyleor error that occurred. SeeMapLoadingError
-
When loading a map, if
prefetchZoomDeltais set to any number greater than 0, the map will first request a tile forzoom - prefetchZoomDeltain an attempt to display a full map at lower resolution as quick as possible.It will get clamped at the tile source minimum zoom. The default delta is 4.
Declaration
Swift
public var prefetchZoomDelta: UInt8 { get set } -
The memory budget hint to be used by the map. The budget can be given in tile units or in megabytes. A Map will do its best to keep the memory allocations for non-essential resources within the budget.
The memory budget distribution and resource eviction logic is subject to change. Current implementation sets a memory budget hint per data source.
If nil is set, the memory budget in tile units will be dynamically calculated based on the current viewport size.
Declaration
Swift
@_spi(Experimental) public func setMemoryBudget(_ memoryBudget: MapMemoryBudget?)Parameters
memoryBudgetThe memory budget hint to be used by the Map.
-
Enables or disables the experimental render cache feature.
Render cache is an experimental feature aiming to reduce resource usage of map rendering by caching intermediate rendering results of tiles into specific cache textures for reuse between frames. Performance benefit of the cache depends on the style as not all layers are cacheable due to e.g. viewport aligned features. Render cache always prefers quality over performance.
Declaration
Swift
@_spi(Experimental) public func setRenderCache(_ cacheOptions: RenderCacheOptions)Parameters
cacheOptionsThe cache options to be set to the Map.
-
Gets the resource options for the map.
All optional fields of the returned object are initialized with the actual values.
Note
The result of this property is different from theResourceOptionsthat were provided to the map’s initializer.Declaration
Swift
public var resourceOptions: ResourceOptions { get } -
Clears temporary map data.
Clears temporary map data from the data path defined in the given resource options. Useful to reduce the disk usage or in case the disk cache contains invalid data.
Note
Calling this API will affect all maps that use the same data path and does not affect persistent map data like offline style packages.
Declaration
Swift
public static func clearData(for resourceOptions: ResourceOptions, completion: @escaping (Error?) -> Void)Parameters
resourceOptionsThe
resource optionsthat contain the map data path to be usedcompletionCalled once the request is complete
-
Gets elevation for the given coordinate.
Note
Elevation is only available for the visible region on the screen.
Declaration
Swift
public func elevation(at coordinate: CLLocationCoordinate2D) -> Double?Parameters
coordinateCoordinate for which to return the elevation.
Return Value
Elevation (in meters) multiplied by current terrain exaggeration, or empty if elevation for the coordinate is not available.
-
Transforms a view’s frame into a set of coordinate bounds
Declaration
Swift
public func coordinateBounds(for rect: CGRect) -> CoordinateBoundsParameters
rectThe
rectwhose bounds will be transformed into a set of map coordinate bounds.Return Value
A
CoordinateBoundsobject that represents the southwest and northeast corners of the view’s bounds. -
Transforms a set of map coordinate bounds to a
CGRectrelative to theMapView.Declaration
Swift
public func rect(for coordinateBounds: CoordinateBounds) -> CGRectParameters
coordinateBoundsThe
coordinateBoundsthat will be converted into a rect relative to theMapViewReturn Value
A
CGRectwhose corners represent the vertices of a set ofCoordinateBounds.
-
The array of
MapDebugOptions. Setting this property to an empty array disables previously enabledMapDebugOptions. The default value is an empty array.Declaration
Swift
public var debugOptions: [MapDebugOptions] { get set } -
Returns the map’s options
Declaration
Swift
public var options: MapOptions { get } -
Calculates a
CameraOptionsto fit aCoordinateBoundsThis API isn’t supported by Globe projection.
Declaration
Swift
public func camera(for coordinateBounds: CoordinateBounds, padding: UIEdgeInsets, bearing: Double?, pitch: Double?) -> CameraOptionsParameters
coordinateBoundsThe coordinate bounds that will be displayed within the viewport.
paddingThe new padding to be used by the camera.
bearingThe new bearing to be used by the camera.
pitchThe new pitch to be used by the camera.
Return Value
A
CameraOptionsthat fits the provided constraints -
Calculates a
CameraOptionsto fit a list of coordinates.This API isn’t supported by Globe projection.
Declaration
Swift
public func camera(for coordinates: [CLLocationCoordinate2D], padding: UIEdgeInsets, bearing: Double?, pitch: Double?) -> CameraOptionsParameters
coordinatesArray of coordinates that should fit within the new viewport.
paddingThe new padding to be used by the camera.
bearingThe new bearing to be used by the camera.
pitchThe new pitch to be used by the camera.
Return Value
A
CameraOptionsthat fits the provided constraints -
Calculates a
CameraOptionsto fit a list of coordinates into a sub-rect of the map.Adjusts the zoom of
camerato fitcoordinatesintorect.Returns the provided camera with zoom adjusted to fit coordinates into
rect, so that the coordinates on the left, top and right of the effective camera center at the principal point of the projection (defined by padding) fit into the rect.This API isn’t supported by Globe projection.
Note
This method may fail if the principal point of the projection is not inside
rector if there is insufficient screen space, defined by principal point and rect, to fit the geometry.Declaration
Swift
public func camera(for coordinates: [CLLocationCoordinate2D], camera: CameraOptions, rect: CGRect) -> CameraOptionsParameters
coordinatesThe coordinates to frame within
rect.cameraThe camera for which the zoom should be adjusted to fit
coordinates.camera.centermust be non-nil.rectThe rectangle inside of the map that should be used to frame
coordinates.Return Value
A
CameraOptionsthat fits the provided constraints, orcameraOptionsif an error occurs. -
Calculates a
CameraOptionsto fit a geometryThis API isn’t supported by Globe projection.
Declaration
Swift
public func camera(for geometry: Geometry, padding: UIEdgeInsets, bearing: CGFloat?, pitch: CGFloat?) -> CameraOptionsParameters
geometryThe geoemtry that will be displayed within the viewport.
paddingThe new padding to be used by the camera.
bearingThe new bearing to be used by the camera.
pitchThe new pitch to be used by the camera.
Return Value
A
CameraOptionsthat fits the provided constraints
-
Returns the coordinate bounds corresponding to a given
CameraOptionsThis API isn’t supported by Globe projection.
Declaration
Swift
public func coordinateBounds(for camera: CameraOptions) -> CoordinateBoundsParameters
cameraThe camera for which the coordinate bounds will be returned.
Return Value
CoordinateBoundsfor the givenCameraOptions -
Returns the unwrapped coordinate bounds to a given
CameraOptions.This function is particularly useful, if the camera shows the antimeridian.
This API isn’t supported by Globe projection.
Declaration
Swift
public func coordinateBoundsUnwrapped(for camera: CameraOptions) -> CoordinateBoundsParameters
cameraThe camera for which the coordinate bounds will be returned.
Return Value
CoordinateBoundsfor the givenCameraOptions. -
Returns the coordinate bounds and zoom for a given
CameraOptions.This API isn’t supported by Globe projection.
Declaration
Swift
public func coordinateBoundsZoom(for camera: CameraOptions) -> CoordinateBoundsZoomParameters
cameraThe camera for which the
CoordinateBoundsZoomwill be returned.Return Value
CoordinateBoundsZoomfor the givenCameraOptions -
Returns the unwrapped coordinate bounds and zoom for a given
CameraOptions.This function is particularly useful, if the camera shows the antimeridian.
This API isn’t supported by Globe projection.
Declaration
Swift
public func coordinateBoundsZoomUnwrapped(for camera: CameraOptions) -> CoordinateBoundsZoomParameters
cameraThe camera for which the
CoordinateBoundsZoomwill be returned.Return Value
CoordinateBoundsZoomfor the givenCameraOptions
-
Converts a point in the mapView’s coordinate system to a geographic coordinate. The point must exist in the coordinate space of the
MapViewThis API isn’t supported by Globe projection.
Declaration
Swift
public func coordinate(for point: CGPoint) -> CLLocationCoordinate2DParameters
pointThe point to convert. Must exist in the coordinate space of the
MapViewReturn Value
A
CLLocationCoordinatethat represents the geographic location of the point. -
Converts a map coordinate to a
CGPoint, relative to theMapView.This API isn’t supported by Globe projection.
Declaration
Swift
public func point(for coordinate: CLLocationCoordinate2D) -> CGPointParameters
coordinateThe coordinate to convert.
Return Value
A
CGPointrelative to theUIView. If the point is outside of the bounds ofMapViewthe returned point contains-1.0for both coordinates. -
Converts map coordinates to an array of
CGPoint, relative to theMapView.This API isn’t supported by Globe projection.
Declaration
Swift
public func points(for coordinates: [CLLocationCoordinate2D]) -> [CGPoint]Parameters
coordinatesThe coordinate to convert.
Return Value
An array of
CGPointrelative to theUIView. If a coordinate's point is outside of map view's bounds, it will be(-1, -1)` -
Converts points in the mapView’s coordinate system to geographic coordinates. The points must exist in the coordinate space of the
MapView.This API isn’t supported by Globe projection.
Declaration
Swift
public func coordinates(for points: [CGPoint]) -> [CLLocationCoordinate2D]Parameters
pointThe point to convert. Must exist in the coordinate space of the
MapViewReturn Value
A
CLLocationCoordinatethat represents the geographic location of the point.
-
Changes the map view by any combination of center, zoom, bearing, and pitch, without an animated transition. The map will retain its current values for any details not passed via the camera options argument. It is not guaranteed that the provided
CameraOptionswill be set, the map may apply constraints resulting in a differentCameraState.Important
This method does not cancel existing animations. Call
CameraAnimationsManager.cancelAnimations()to cancel existing animations.Declaration
Swift
public func setCamera(to cameraOptions: CameraOptions)Parameters
cameraOptionsNew camera options
-
Returns the current camera state
Declaration
Swift
public var cameraState: CameraState { get } -
Sets/get the map view with the free camera options.
FreeCameraOptions provides more direct access to the underlying camera entity. For backwards compatibility the state set using this API must be representable with
CameraOptionsas well. Parameters are clamped to a valid range or discarded as invalid if the conversion to the pitch and bearing presentation is ambiguous. For example orientation can be invalid if it leads to the camera being upside down or the quaternion has zero length.Declaration
Swift
public var freeCameraOptions: FreeCameraOptions { get set }Parameters
freeCameraOptionsThe free camera options to set.
-
Returns the bounds of the map.
Declaration
Swift
public var cameraBounds: CameraBounds { get } -
Sets the bounds of the map.
Throws
MapErrorDeclaration
Swift
public func setCameraBounds(with options: CameraBoundsOptions) throwsParameters
optionsNew camera bounds. Nil values will not take effect.
-
Prepares the drag gesture to use the provided screen coordinate as a pivot point. This function should be called each time when user starts a dragging action (e.g. by clicking on the map). The following dragging will be relative to the pivot.
Declaration
Swift
public func dragStart(for point: CGPoint)Parameters
pointScreen point
-
Calculates target point where camera should move after drag. The method should be called after
dragStartand beforedragEnd.Declaration
Swift
public func dragCameraOptions(from: CGPoint, to: CGPoint) -> CameraOptionsParameters
fromPointThe point from which the map is dragged.
toPointThe point to which the map is dragged.
Return Value
The camera options object showing end point.
-
Ends the ongoing drag gesture. This function should be called always after the user has ended a drag gesture initiated by
dragStart.Declaration
Swift
public func dragEnd()
-
If implementing a custom animation mechanism, call this method when the animation begins. Must always be paired with a corresponding call to
endAnimation()Declaration
Swift
public func beginAnimation() -
If implementing a custom animation mechanism, call this method when the animation ends. Must always be paired with a corresponding call to
beginAnimation()Declaration
Swift
public func endAnimation() -
If implementing a custom gesture, call this method when the gesture begins. Must always be paired with a corresponding call to
endGesture()Declaration
Swift
public func beginGesture() -
If implementing a custom gesture, call this method when the gesture ends. Must always be paired with a corresponding call to
beginGesture()Declaration
Swift
public func endGesture()
-
Queries the map for rendered features.
Declaration
Swift
@available(*, deprecated, renamed: "queryRenderedFeatures(with:options:completion:﹚") public func queryRenderedFeatures(for shape: [CGPoint], options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void)Parameters
shapeScreen point coordinates (point, line string or box) to query for rendered features.
optionsOptions for querying rendered features.
completionCallback called when the query completes
-
Undocumented
Declaration
Swift
@discardableResult public func queryRenderedFeatures(with shape: [CGPoint], options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void) -> Cancelable -
Queries the map for rendered features.
Declaration
Swift
@available(*, deprecated, renamed: "queryRenderedFeatures(with:options:completion:﹚") public func queryRenderedFeatures(in rect: CGRect, options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void)Parameters
rectScreen rect to query for rendered features.
optionsOptions for querying rendered features.
completionCallback called when the query completes
-
Undocumented
Declaration
Swift
@discardableResult public func queryRenderedFeatures(with rect: CGRect, options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void) -> Cancelable -
Queries the map for rendered features.
Declaration
Swift
@available(*, deprecated, renamed: "queryRenderedFeatures(with:options:completion:﹚") public func queryRenderedFeatures(at point: CGPoint, options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void)Parameters
pointScreen point at which to query for rendered features.
optionsOptions for querying rendered features.
completionCallback called when the query completes
-
Undocumented
Declaration
Swift
@discardableResult public func queryRenderedFeatures(with point: CGPoint, options: RenderedQueryOptions? = nil, completion: @escaping (Result<[QueriedFeature], Error>) -> Void) -> Cancelable -
Queries the map for source features.
Declaration
Swift
public func querySourceFeatures(for sourceId: String, options: SourceQueryOptions, completion: @escaping (Result<[QueriedFeature], Error>) -> Void)Parameters
sourceIdStyle source identifier used to query for source features.
optionsOptions for querying source features.
completionCallback called when the query completes
-
Queries for feature extension values in a GeoJSON source.
1. `children`: returns the children of a cluster (on the next zoom level). 2. `leaves`: returns all the leaves of a cluster (given its cluster_id) 3. `expansion-zoom`: returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature).- args: Used for further query specification when using ‘leaves’ extensionField. Now only support following two args:
1. `limit`: the number of points to return from the query (must use type 'UInt64', set to maximum for all points) 2. `offset`: the amount of points to skip (for pagination, must use type 'UInt64')- completion: The result could be a feature extension value containing either a value (expansion-zoom) or a feature collection (children or leaves). An error is passed if the operation was not successful. Deprecated. Use getGeoJsonClusterLeaves/getGeoJsonClusterChildren/getGeoJsonClusterExpansionZoom to instead.
Declaration
Swift
public func queryFeatureExtension(for sourceId: String, feature: Feature, extension: String, extensionField: String, args: [String: Any]? = nil, completion: @escaping (Result<FeatureExtensionValue, Error>) -> Void)Parameters
sourceIdThe identifier of the source to query.
featureFeature to look for in the query.
extensionCurrently supports keyword
supercluster.extensionFieldCurrently supports following three extensions:
argsUsed for further query specification when using ‘leaves’ extensionField. Now only support following two args:
completionThe result could be a feature extension value containing either a value (expansion-zoom) or a feature collection (children or leaves). An error is passed if the operation was not successful. Deprecated. Use getGeoJsonClusterLeaves/getGeoJsonClusterChildren/getGeoJsonClusterExpansionZoom to instead.
-
Returns all the leaves (original points) of a cluster (given its cluster_id) from a GeoJSON source, with pagination support: limit is the number of leaves to return (set to Infinity for all points), and offset is the amount of points to skip (for pagination).
Declaration
Swift
public func getGeoJsonClusterLeaves(forSourceId sourceId: String, feature: Feature, limit: UInt64 = 10, offset: UInt64 = 0, completion: @escaping (Result<FeatureExtensionValue, Error>) -> Void)Parameters
sourceIdThe identifier of the source to query.
featureFeature to look for in the query.
limitthe number of points to return from the query, default to 10
offsetthe amount of points to skip, default to 0
completionThe result could be a feature extension value containing either a value (expansion-zoom) or a feature collection (children or leaves). An error is passed if the operation was not successful.
-
Returns the children (original points or clusters) of a cluster (on the next zoom level) given its id (cluster_id value from feature properties) from a GeoJSON source.
Declaration
Swift
public func getGeoJsonClusterChildren(forSourceId sourceId: String, feature: Feature, completion: @escaping (Result<FeatureExtensionValue, Error>) -> Void)Parameters
sourceIdThe identifier of the source to query.
featureFeature to look for in the query.
completionThe result could be a feature extension value containing either a value (expansion-zoom) or a feature collection (children or leaves). An error is passed if the operation was not successful.
-
Returns the zoom on which the cluster expands into several children (useful for “click to zoom” feature) given the cluster’s cluster_id (cluster_id value from feature properties) from a GeoJSON source.
Declaration
Swift
public func getGeoJsonClusterExpansionZoom(forSourceId sourceId: String, feature: Feature, completion: @escaping (Result<FeatureExtensionValue, Error>) -> Void)Parameters
sourceIdThe identifier of the source to query.
featureFeature to look for in the query.
completionThe result could be a feature extension value containing either a value (expansion-zoom) or a feature collection (children or leaves). An error is passed if the operation was not successful.
-
Subscribes an observer to a list of events.
MapboxMapholds a strong reference toobserverwhile it is subscribed. To stop receiving notifications, pass the sameobservertounsubscribe(_:events:).Note
Prefer
onNext(eventTypes:handler:),onNext(_:handler:), andonEvery(_:handler:)to using this lower-level APIsDeclaration
Swift
public func subscribe(_ observer: Observer, events: [String])Parameters
observerAn object that will receive events of the types specified by
eventseventsArray of event types to deliver to
observer -
Unsubscribes an observer from a provided list of event types.
MapboxMapholds a strong reference toobserverwhile it is subscribed. To stop receiving notifications, pass the sameobserverto this method as was passed tosubscribe(_:events:).Declaration
Swift
public func unsubscribe(_ observer: Observer, events: [String] = [])Parameters
observerThe object to unsubscribe
eventsArray of event types to unsubscribe from. Pass an empty array (the default) to unsubscribe from all events.
-
Listen to a single occurrence of a Map event.
This will observe the next (and only the next) event of the specified type. After observation, the underlying subscriber will unsubscribe from the map or snapshotter.
If you need to unsubscribe before the event fires, call
cancel()on the returnedCancelableobject.Declaration
Swift
@discardableResult public func onNext<Payload>(event eventType: MapEvents.Event<Payload>, handler: @escaping (MapEvent<Payload>) -> Void) -> Cancelable where Payload : DecodableParameters
eventTypeThe event type to listen to.
handlerThe closure to execute when the event occurs.
Return Value
A
Cancelableobject that you can use to stop listening for the event. This is especially important if you have a retain cycle in the handler. -
Listen to a single occurrence of a Map event.
This will observe the next (and only the next) event of the specified type. After observation, the underlying subscriber will unsubscribe from the map or snapshotter.
If you need to unsubscribe before the event fires, call
cancel()on the returnedCancelableobject.Declaration
Swift
@available(*, deprecated, renamed: "onNext(event:handler:﹚") @discardableResult public func onNext(_ eventType: MapEvents.EventKind, handler: @escaping (Event) -> Void) -> CancelableParameters
eventTypeThe event type to listen to.
handlerThe closure to execute when the event occurs.
Return Value
A
Cancelableobject that you can use to stop listening for the event. This is especially important if you have a retain cycle in the handler. -
Listen to multiple occurrences of a Map event.
Declaration
Swift
@available(*, deprecated, renamed: "onEvery(event:handler:﹚") @discardableResult public func onEvery(_ eventType: MapEvents.EventKind, handler: @escaping (Event) -> Void) -> CancelableParameters
eventTypeThe event type to listen to.
handlerThe closure to execute when the event occurs.
Return Value
A
Cancelableobject that you can use to stop listening for events. This is especially important if you have a retain cycle in the handler. -
Listen to multiple occurrences of a Map event.
Declaration
Swift
@discardableResult public func onEvery<Payload>(event: MapEvents.Event<Payload>, handler: @escaping (MapEvent<Payload>) -> Void) -> Cancelable where Payload : DecodableParameters
eventTypeThe event type to listen to.
handlerThe closure to execute when the event occurs.
Return Value
A
Cancelableobject that you can use to stop listening for events. This is especially important if you have a retain cycle in the handler.
-
Clears temporary map data.
Clears temporary map data from the data path defined in the given resource options. Useful to reduce the disk usage or in case the disk cache contains invalid data.
Note
Calling this API will affect all maps that use the same data path and does not affect persistent map data like offline style packages.
Declaration
Swift
public func clearData(completion: @escaping (Error?) -> Void)Parameters
completionCalled once the request is complete
-
Update the state map of a feature within a style source. Update entries in the state map of a given feature within a style source. Only entries listed in the state map will be updated. An entry in the feature state map that is not listed in
statewill retain its previous value.Declaration
Swift
public func setFeatureState(sourceId: String, sourceLayerId: String? = nil, featureId: String, state: [String : Any])Parameters
sourceIdStyle source identifier
sourceLayerIdStyle source layer identifier (for multi-layer sources such as vector sources). Defaults to
nil.featureIdIdentifier of the feature whose state should be updated
stateMap of entries to update with their respective new values
-
Get the state map of a feature within a style source.
Declaration
Swift
public func getFeatureState(sourceId: String, sourceLayerId: String? = nil, featureId: String, callback: @escaping (Result<[String : Any], Error>) -> Void)Parameters
sourceIdStyle source identifier.
sourceLayerIdStyle source layer identifier (for multi-layer sources such as vector sources).
featureIdIdentifier of the feature whose state should be queried.
callbackFeature’s state map or an empty map if the feature could not be found.
-
Removes entries from a feature state object. Remove a specified property or all property from a feature’s state object, depending on the value of
stateKey.Declaration
Swift
public func removeFeatureState(sourceId: String, sourceLayerId: String? = nil, featureId: String, stateKey: String? = nil)Parameters
sourceIdThe style source identifier
sourceLayerIdThe style source layer identifier (for multi-layer sources such as vector sources). Defaults to
nil.featureIdThe feature identifier of the feature whose state should be removed.
stateKeyThe key of the property to remove. If
nil, all feature’s state object properties are removed. Defaults tonil.
-
Undocumented
Declaration
Swift
@_spi(Internal) public final func makeRecorder() -> MapRecorder
MapboxMap Class Reference