Swiftpack.co - Package - mapbox/MapboxStatic.swift

MapboxStatic

CircleCI Carthage compatible CocoaPods

MapboxStatic.swift makes it easy to connect your iOS, macOS, tvOS, or watchOS application to the Mapbox Static Images API or the Legacy Static Images API. Quickly generate a map snapshot – a static map image with overlays – by fetching it synchronously or asynchronously over the Web using first-class Swift or Objective-C data types.

A snapshot is a flattened PNG or JPEG image, ideal for use in a table or image view, user notification, sharing service, printed document, or anyplace else you’d like a quick, custom map without the overhead of an interactive view. A static map is created in a single HTTP request. Overlays are added server-side.

MapboxStatic.swift pairs well with MapboxDirections.swift, MapboxGeocoder.swift, the Mapbox Maps SDK for iOS, and the Mapbox Maps SDK for macOS SDK. If you’re already using the maps SDK for iOS or macOS for other purposes, consider using an MGLMapSnapshotter object instead of MapboxStatic.swift to produce static images that take advantage of caching and offline packs.

System requirements

  • One of the following package managers:
    • CocoaPods (CocoaPods 1.10 or above if using Xcode 12)
    • Carthage 0.19 or above (run this script instead of carthage if using Xcode 12)
    • Swift Package Manager 5.3 or above
  • Xcode 11 or above (Xcode 12 or above if using Swift Package Manager)
  • One of the following operating systems:
    • iOS 10.0 or above
    • macOS 10.12.0 or above
    • tvOS 10.0 or above
    • watchOS 3.0 or above

Installation

Carthage

Specify the following dependency in your Carthage Cartfile:

github "mapbox/MapboxStatic.swift" ~> 0.11

CocoaPods

In your CocoaPods Podfile:

pod 'MapboxStatic.swift', '~> 0.11'

Swift Package Manager

To install MapboxStatic using the Swift Package Manager, add the following package to the dependencies in your Package.swift file:

.package(url: "https://github.com/mapbox/MapboxStatic.swift.git", .branch("main")),

Then import MapboxStatic or @import MapboxStatic;.

This repository includes an example iOS application written in Swift, as well as Swift playgrounds for iOS and macOS. To run them, you need to use Carthage 0.19 or above to install the dependencies. Open the playgrounds inside of MapboxStatic.xcworkspace. More examples are available in the Mapbox API Documentation.

Usage

You can generate a snapshot from either a Mapbox-hosted style or a raw tile set. Using a style gives you more visual options like rotation, while using a tile set gives you a choice of image formats. If you’re working with vector data, you’ll want to use a style; if you’re working with a single raster imagery source, you may want to use a tile set.

To generate a snapshot from a style, you’ll need its style URL. You can either choose a Mapbox-designed style or design one yourself in Mapbox Studio. You can use the same style within the Mapbox Maps SDK for iOS or macOS.

To generate a snapshot from a tile set, you’ll need a map ID. You can either choose a Mapbox-maintained tile set or upload your own to Mapbox Studio.

You’ll also need an access token with the styles:tiles scope enabled in order to use this library. You can specify your access token inline or by setting the MGLMapboxAccessToken key in your application’s Info.plist file.

The examples below are each provided in Swift (denoted with main.swift) and Objective-C (main.m). For further details, see the MapboxStatic.swift API reference.

Basics

The main static map class is Snapshot in Swift or MBSnapshot in Objective-C. To create a basic snapshot, create a SnapshotOptions object, specifying snapshot camera (viewpoint) and point size:

// main.swift
import MapboxStatic

let camera = SnapshotCamera(
    lookingAtCenter: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
    zoomLevel: 12)
let options = SnapshotOptions(
    styleURL: URL(string: "<#your mapbox: style URL#>")!,
    camera: camera,
    size: CGSize(width: 200, height: 200))
let snapshot = Snapshot(
    options: options,
    accessToken: "<#your access token#>")
// main.m
@import MapboxStatic;

NSURL *styleURL = [NSURL URLWithString:@"<#your mapbox: style URL#>"];
MBSnapshotCamera *camera = [MBSnapshotCamera cameraLookingAtCenterCoordinate:CLLocationCoordinate2DMake(45.52, -122.681944)
                                                                   zoomLevel:12];
MBSnapshotOptions *options = [[MBSnapshotOptions alloc] initWithStyleURL:styleURL
                                                                  camera:camera
                                                                    size:CGSizeMake(200, 200)];
MBSnapshot *snapshot = [[MBSnapshot alloc] initWithOptions:options
                                               accessToken:@"<#your access token#>"];

Then, you can either retrieve an image synchronously (blocking the calling thread):

// main.swift
imageView.image = snapshot.image
// main.m
imageView.image = snapshot.image;

Or you can pass a completion handler to update the UI thread after the image is retrieved:

// main.swift
snapshot.image { (image, error) in
    imageView.image = image
}
// main.m
[snapshot imageWithCompletionHandler:^(UIImage * _Nullable image, NSError * _Nullable error) {
    imageView.image = image;
}];

If you're using your own HTTP library or routines, you can also retrieve a snapshot’s URL property.

// main.swift
let imageURL = snapshot.url
// main.m
NSURL *imageURL = snapshot.url;

To create a basic classic snapshot, create a ClassicSnapshotOptions or MBClassicSnapshotOptions object, specifying the center coordinates, zoom level, and size in points:

// main.swift
let options = ClassicSnapshotOptions(
    mapIdentifiers: ["<#your map ID#>"],
    centerCoordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
    zoomLevel: 13,
    size: CGSize(width: 300, height: 200))
let snapshot = Snapshot(
    options: options,
    accessToken: "<#your access token#>")
imageView.image = snapshot.image
// main.m
MBSnapshotOptions *options = [[MBClassicSnapshotOptions alloc] initWithMapIdentifiers:@[@"<#your map ID#>"]
                                                                     centerCoordinate:CLLocationCoordinate2DMake(45.52, -122.681944)
                                                                            zoomLevel:13
                                                                                 size:CGSizeMake(200, 200)];
MBSnapshot *snapshot = [[MBSnapshot alloc] initWithOptions:options accessToken:@"<#your access token#>"];
imageView.image = snapshot.image;

Overlays

Overlays are where things get interesting! You can add Maki markers, custom marker imagery, GeoJSON geometries, and even paths made of bare coordinates.

You add overlays to the overlays field in the SnapshotOptions or MBSnapshotOptions object. Here are some versions of our snapshot with various overlays added.

Marker

// main.swift
let markerOverlay = Marker(
    coordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
    size: .medium,
    iconName: "cafe"
)
markerOverlay.color = .brown
// main.m
MBMarker *markerOverlay = [[MBMarker alloc] initWithCoordinate:CLLocationCoordinate2DMake(45.52, -122.681944)
                                                          size:MBMarkerSizeMedium
                                                      iconName:@"cafe"];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
    markerOverlay.color = [UIColor brownColor];
#elif TARGET_OS_MAC
    markerOverlay.color = [NSColor brownColor];
#endif

Custom marker

// main.swift
let customMarker = CustomMarker(
    coordinate: CLLocationCoordinate2D(latitude: 45.522, longitude: -122.69),
    url: URL(string: "https://www.mapbox.com/help/img/screenshots/rocket.png")!
)
// main.m
NSURL *url = [NSURL URLWithString:@"https://www.mapbox.com/help/img/screenshots/rocket.png"];
MBCustomMarker *customMarker = [[MBCustomMarker alloc] initWithCoordinate:CLLocationCoordinate2DMake(45.522, -122.69)
                                                                      url:url];

GeoJSON

// main.swift
let geoJSONOverlay: GeoJSON

do {
    let geoJSONURL = URL(string: "http://git.io/vCv9U")!
    let geoJSONString = try String(contentsOf: geoJSONURL, encoding: .utf8)
    geoJSONOverlay = GeoJSON(objectString: geoJSONString)
}
// main.m
NSURL *geoJSONURL = [NSURL URLWithString:@"http://git.io/vCv9U"];
NSString *geoJSONString = [[NSString alloc] initWithContentsOfURL:geoJSONURL
                                                         encoding:NSUTF8StringEncoding
                                                            error:NULL];
MBGeoJSON *geoJSONOverlay = [[MBGeoJSON alloc] initWithObjectString:geoJSONString];

Path

// main.swift
let path = Path(
    coordinates: [
        CLLocationCoordinate2D(
            latitude: 45.52475063103141, longitude: -122.68209457397461
        ),
        CLLocationCoordinate2D(
            latitude: 45.52451009822193, longitude: -122.67488479614258
        ),
        CLLocationCoordinate2D(
            latitude: 45.51681250530043, longitude: -122.67608642578126
        ),
        CLLocationCoordinate2D(
            latitude: 45.51693278828882, longitude: -122.68999099731445
        ),
        CLLocationCoordinate2D(
            latitude: 45.520300607576864, longitude: -122.68964767456055
        ),
        CLLocationCoordinate2D(
            latitude: 45.52475063103141, longitude: -122.68209457397461
        )
    ]
)
path.strokeWidth = 2
path.strokeColor = .black
#if os(macOS)
    path.fillColor = NSColor.red.withAlphaComponent(0.25)
#else
    path.fillColor = UIColor.red.withAlphaComponent(0.25)
#endif
// main.m
CLLocationCoordinate2D coordinates[] = {
    CLLocationCoordinate2DMake(45.52475063103141, -122.68209457397461),
    CLLocationCoordinate2DMake(45.52451009822193, -122.67488479614258),
    CLLocationCoordinate2DMake(45.51681250530043, -122.67608642578126),
    CLLocationCoordinate2DMake(45.51693278828882, -122.68999099731445),
    CLLocationCoordinate2DMake(45.520300607576864, -122.68964767456055),
    CLLocationCoordinate2DMake(45.52475063103141, -122.68209457397461),
};
MBPath *path = [[MBPath alloc] initWithCoordinates:coordinates
                                             count:sizeof(coordinates) / sizeof(coordinates[0])];
path.strokeWidth = 2;
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
    path.strokeColor = [UIColor blackColor];
    path.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.25];
#elif TARGET_OS_MAC
    path.strokeColor = [NSColor blackColor];
    path.fillColor = [[NSColor redColor] colorWithAlphaComponent:0.25];
#endif

Other options

Rotation and tilt

To rotate and tilt a snapshot, set its camera’s heading and pitch:

// main.swift
let camera = SnapshotCamera(
    lookingAtCenter: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
    zoomLevel: 13)
camera.heading = 45
camera.pitch = 60
let options = SnapshotOptions(
    styleURL: URL(string: "<#your mapbox: style URL#>")!,
    camera: camera,
    size: CGSize(width: 200, height: 200))
let snapshot = Snapshot(
    options: options,
    accessToken: "<#your access token#>")
// main.m
NSURL *styleURL = [NSURL URLWithString:@"<#your mapbox: style URL#>"];
MBSnapshotCamera *camera = [MBSnapshotCamera cameraLookingAtCenterCoordinate:CLLocationCoordinate2DMake(45.52, -122.681944)
                                                                   zoomLevel:13];
camera.heading = 45;
camera.pitch = 60;
MBSnapshotOptions *options = [[MBSnapshotOptions alloc] initWithStyleURL:styleURL
                                                                  camera:camera
                                                                    size:CGSizeMake(200, 200)];
MBSnapshot *snapshot = [[MBSnapshot alloc] initWithOptions:options
                                               accessToken:@"<#your access token#>"];

Auto-fitting features

If you’re adding overlays to a snapshot, leave out the center coordinate and zoom level to automatically calculate the center and zoom level that best shows them off.

// main.swift

let options = SnapshotOptions(
    styleURL: URL(string: "<#your mapbox: style URL#>")!,
    size: CGSize(width: 500, height: 300))
options.overlays = [path, geojsonOverlay, markerOverlay, customMarker]
// main.m
NSURL *styleURL = [NSURL URLWithString:@"<#your mapbox: style URL#>"];
MBSnapshotOptions *options = [[MBClassicSnapshotOptions alloc] initWithStyleURL:styleURL
                                                                           size:CGSizeMake(500, 300)];
options.overlays = @[path, geojsonOverlay, markerOverlay, customMarker];

Standalone markers

Use the MarkerOptions class to get a standalone marker image, which can be useful if you’re trying to composite it atop a map yourself.

// main.swift
let options = MarkerOptions(
    size: .medium,
    iconName: "cafe")
options.color = .brown
let snapshot = Snapshot(
    options: options,
    accessToken: "<#your access token#>")
// main.m
MBMarkerOptions *options = [[MBMarkerOptions alloc] initWithSize:MBMarkerSizeMedium
                                                        iconName:@"cafe"];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
    options.color = [UIColor brownColor];
#elif TARGET_OS_MAC
    options.color = [NSColor brownColor];
#endif
MBSnapshot *snapshot = [[MBSnapshot alloc] initWithOptions:options
                                               accessToken:@"<#your access token#>"];

File format and quality

When creating a classic snapshot, you can also specify PNG or JPEG image format as well as various bandwidth-saving image qualities.

Attribution

Be sure to attribute your map properly in your application. You can also find out more about where Mapbox’s map data comes from.

Tests

To run the included unit tests, you need to use Carthage 0.19 or above to install the dependencies.

  1. carthage bootstrap
  2. open MapboxStatic.xcodeproj
  3. Go to Product ‣ Test.

Github

link
Stars: 157

Used By

Total: 0

Releases

v0.11.0 -

Changes since v0.10.0:

  • This library can now be installed using Swift Package Manager. (#96)
  • Renamed ClassicSnapshotOptions(mapIdentifiers:size:) to ClassicSnapshotOptions(tileSetIdentifiers:size:) and ClassicSnapshotOptions(mapIdentifiers:zoomLevel:size:) to ClassicSnapshotOptions(tileSetIdentifiers:zoomLevel:size:). (#100)
  • Migrated to Swift 5. (#101)

v0.10.0 -

Changes since v0.9.1:

  • This library now depends on the Polyline framework. (#53)
  • Upgraded to Swift 4. (#75)
  • Added support for watchOS on the fourth-generation Apple Watch. (#82)

v0.9.1 -

Changes since v0.9.0:

  • Fixed a crash that could occur if another module extends UIColor with a toHexString() method. (#66)

v0.9.0 -

Changes since v0.8.0:

  • Removed the strokeOpacity and fillOpacity properties from Path in favor of the alpha components of the strokeColor and fillColor properties, respectively. (#61)
  • Fixed a linker error in Objective-C projects about “incompatible Objective-C category definitions”. (#60)
  • Fixed an issue causing Path overlays without fills to become closed polygons. (#58)

v0.8.0 -

This release upgrades the library to the Mapbox Static API, which is powered by Mapbox GL. Snapshot modern styles, rotated and tilted, with all the same overlay options as before (#54). Changes since v0.7.0:

  • SnapshotOptions’ initializers have been replaced with new initializers that accept a style URL and SnapshotCamera. (SnapshotCamera is similar to MGLMapCamera in the Mapbox iOS and macOS SDKs, except that you can specify either a zoom level or an altitude for convenience.)
  • ClassicSnapshotOptions connects to the classic Static API, retaining the functionality of the former SnapshotOptions.
  • Overlay options have remained relatively unchanged, although markers now support a wider selection of icon names in conjunction with SnapshotOptions, and you can choose to insert overlays below labels, roads, or other parts of the map.
  • SnapshotOptions adds a Mapbox logo and copyright notices by default.
  • GeoJSON(object:) is once again throwable.
  • Fixed warnings building with Swift 3.1. (#55)

v0.7.0 -

Changes since v0.6.2:

  • Migrated to Swift 3.0. If your application is written in Swift 2.3, you should stick to v0.6.x or use the swift2.3 branch. (#50)
  • Fixed an issue causing the error “The sandbox is not in sync with the Podfile.lock” when updating a Carthage-based project that requires this framework. (#51)

v0.6.2 -

Changes since v0.6.1:

  • Migrated to Swift 2.3.
  • Fixed an error that occurred when archiving an application that links to this library. (#38)
  • The user agent string sent by the Mac version of this library now says “macOS” instead of “OS X”. (#36)
  • More reliably parse server responses. (#40)
  • Clarified documentation. (#39)

To install this release via CocoaPods, point your Podfile to:

pod 'MapboxStatic.swift', :git => 'https://github.com/mapbox/MapboxStatic.swift.git', :tag => 'v0.6.2'

v0.6.1 -

Changes since v0.6.0:

  • When the request fails due to rate limiting, an invalid access token, or other invalid input, the completion handler’s error parameter contains an NSError object with an explanation of the reason for the failure and a recovery suggestion. (#32, #34)
  • Renamed Snapshot.requestURL to simply URL. (#31)
  • Requests sent through this library now use a more specific user agent string, so you can more easily identify this library on your Statistics page in Mapbox Studio. (#33)
  • Fixed a crash when requesting images between 640 and 1,280 points tall or wide on Retina displays.

To install this release via CocoaPods, point your Podfile to:

pod 'MapboxStatic.swift', :git => 'https://github.com/mapbox/MapboxStatic.swift.git', :tag => 'v0.6.1'

v0.6.0 -

Changes since v0.5.0:

  • Added support for bridging to Objective-C code. All classes now inherit from NSObject and have prefixed Objective-C class names. (#28)
  • Even if you aren’t using CocoaPods, you can now install the framework into tvOS and watchOS projects in addition to iOS and OS X projects. (#25)
  • Fixed a compiler error that affected watchOS projects that installed this library via CocoaPods. (#25)
  • A new MarkerOptions class conforms to a common SnapshotOptionsProtocol and inherits from MarkerImage like Marker does. MarkerOptions is responsible for configuring a request for a standalone marker from the classic Static API. (#30)
  • Renamed the mapIdentifier parameter of SnapshotOptions’ initializers to reflect the fact that you can composite multiple tile sets together by specifying multiple map identifiers. (#22)
  • Added Markdown documentation throughout the library. (#23, #24)
  • Overlay is now a protocol. (#23)
  • Marker and CustomMarker share a Point protocol. (#23)
  • Renamed MarkerSize to Size and placed it under Marker. (#23)
  • Renamed SnapshotFormat to simply Format and placed it under SnapshotOptions.
  • Added multiple convenience initializers to Marker that replace the label parameter with more specific parameters. (#23, #28)
  • Renamed GeoJSON(string:) to GeoJSON(objectString:) and added a GeoJSON(object:) that takes structured data. (#23)
  • Fixed an issue in which strings containing ? or ) passed into Path’s initializer would truncate the request URL, potentially causing the image request to fail. (#26)
  • Fixed an incorrect assertion failure creating large snapshots on devices with 3× screens. (#27)
  • Removed colors from overlay initializers in order to support multiple operating systems in Objective-C. Also removed other parameters from Path’s initializer since they make less sense without color parameters. (#28)
  • Added members to Path that refer to coordinates with raw pointers instead of arrays to enable bridging to Objective-C with C arrays. (#28)

To install this release via CocoaPods, point your Podfile to:

pod 'MapboxStatic.swift', :git => 'https://github.com/mapbox/MapboxStatic.swift.git', :tag => 'v0.6.0'

v0.5.0 -

Changes since v0.4.0:

  • This library is now distributed as a dynamic framework instead of a standalone source code file. (#16)
  • Added support for Cocoa applications on OS X. (#21)
  • Moved MarkerSize, Overlay, Marker, CustomMarker, GeoJSON, and Path out of MapboxStaticMap and into the module’s namespace. Moved ImageFormat out of MapboxStaticMap and renamed it SnapshotFormat. If any of these class names conflict with a class in your application’s module, prefix it with MapboxStatic.. (#18)
  • Renamed MapboxStaticMap to Snapshot. Snapshot’s initializer takes a SnapshotOptions parameter that specifies the viewport and output format. (#19)
  • If no access token is passed into Snapshot’s initializer, it is read from the MGLMapboxAccessToken key in the main bundle’s Info.plist. (#19)
  • A snapshot’s scale defaults to the screen’s resolution. (#19)
  • Removed the autoFitFeatures option. To have to snapshot automatically fit any overlays, omit its centerCoordinate and zoomLevel. Null Island is no longer the default center coordinate. (#19)
  • Renamed imageWithCompletionHandler(_:) to image(completionHandler:) and added an optional error parameter to the completion handler. (#19)
  • Upgraded to Swift 3–compatible syntax. (#14)

To install this release via CocoaPods, point your Podfile to:

pod 'MapboxStatic.swift', :git => 'https://github.com/mapbox/MapboxStatic.swift.git', :tag => 'v0.5.0'

-

-

-

-