Swift Objective-C Ruby
Latest commit 2163a80 Feb 23, 2017 @1ec5 1ec5 committed on GitHub Use official pod
It’s no longer necessary to use the full git URL.

README.md

MapboxStatic

📱 iOS Build Status     🖥💻 macOS Build Status     📺 tvOS Build Status     ⌚️ watchOS Build Status

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

Static maps are flattened PNG or JPG images, ideal for use in table views, image views, and anyplace else you'd like a quick, custom map without the overhead of an interactive view. They are created in one HTTP request, so overlays are all added server-side.

MapboxStatic.swift pairs well with MapboxDirections.swift, MapboxGeocoder.swift, and the Mapbox iOS SDK or macOS SDK.

Installation

Specify the following dependency in your Carthage Cartfile:

github "Mapbox/MapboxStatic.swift" "~> 0.7"

Or in your CocoaPods Podfile:

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

Then import MapboxStatic or @import MapboxStatic;.

v0.6.2 is the last release of MapboxDirections.swift written in Swift 2.3. The swift2.3 branch corresponds to this release, plus any critical bug fixes that have been applied since. All subsequent releases will be based on the master branch, which is written in Swift 3. The Swift examples below are written in Swift 3; see the swift2.3 branch’s readme for Swift 2.3 examples.

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 will need a map ID from a custom map style on your Mapbox account. You will also need an access token in order to use the API.

Basics

The main static map class is Snapshot in Swift or MBSnapshot in Objective-C. To create a basic snapshot, create a SnapshotOptions or MBSnapshotOptions object, specifying the center coordinates, zoom level, and point size:

// main.swift
import MapboxStatic

let options = SnapshotOptions(
    mapIdentifiers: ["<#your map ID#>"],
    centerCoordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
    zoomLevel: 13,
    size: CGSize(width: 200, height: 200))
let snapshot = Snapshot(
    options: options,
    accessToken: "<#your access token#>")
// main.m
@import MapboxStatic;

MBSnapshotOptions *options = [[MBSnapshotOptions 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#>"];

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;

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
MBCustomMarker *customMarker = [[MBCustomMarker alloc] initWithCoordinate:CLLocationCoordinate2DMake(45.522, -122.69)
                                                                      url:[NSURL URLWithString:@"https://www.mapbox.com/help/img/screenshots/rocket.png"]];

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
path.fillColor = .red
path.fillOpacity = 0.25
// 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];
#elif TARGET_OS_MAC
    path.strokeColor = [NSColor blackColor];
    path.fillColor = [NSColor redColor];
#endif
path.fillOpacity = 0.25;

Other options

Auto-fitting features

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

// main.swift
var options = SnapshotOptions(
    mapIdentifiers: ["<#your map ID#>"],
    size: CGSize(width: 500, height: 300))
options.overlays = [path, geojsonOverlay, markerOverlay, customMarker]
// main.m
MBSnapshotOptions *options = [[MBSnapshotOptions alloc] initWithMapIdentifiers:@[@"<#your map ID#>"]
                                                                          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 map, 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.