This repository has been archived by the owner on Jun 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
StaticSnapshotExample.swift
61 lines (49 loc) · 2.66 KB
/
StaticSnapshotExample.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Mapbox
@objc(StaticSnapshotExample_Swift)
class StaticSnapshotExample: UIViewController, MGLMapViewDelegate {
var mapView: MGLMapView!
var button: UIButton!
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MGLMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height / 2), styleURL: MGLStyle.satelliteStreetsStyleURL)
mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
// Center map on the Giza Pyramid Complex in Egypt.
let center = CLLocationCoordinate2D(latitude: 29.9773, longitude: 31.1325)
mapView.setCenter(center, zoomLevel: 14, animated: false)
view.addSubview(mapView)
// Create a button to take a map snapshot.
button = UIButton(frame: CGRect(x: mapView.bounds.width / 2 - 40, y: mapView.bounds.height - 40, width: 80, height: 30))
button.layer.cornerRadius = 15
button.backgroundColor = UIColor(red: 0.96, green: 0.65, blue: 0.14, alpha: 1.0)
button.setImage(UIImage(named: "camera"), for: .normal)
button.addTarget(self, action: #selector(createSnapshot), for: .touchUpInside)
view.addSubview(button)
// Create a UIImageView that will store the map snapshot.
imageView = UIImageView(frame: CGRect(x: 0, y: view.bounds.height / 2, width: view.bounds.width, height: view.bounds.height / 2))
imageView.backgroundColor = .black
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(imageView)
}
@objc func createSnapshot() {
// Use the map's style, camera, size, and zoom level to set the snapshot's options.
let options = MGLMapSnapshotOptions(styleURL: mapView.styleURL, camera: mapView.camera, size: mapView.bounds.size)
options.zoomLevel = mapView.zoomLevel
// Add an activity indicator to show that the snapshot is loading.
let indicator = UIActivityIndicatorView(frame: CGRect(x: self.imageView.center.x - 30, y: self.imageView.center.y - 30, width: 60, height: 60))
view.addSubview(indicator)
indicator.startAnimating()
// Create the map snapshot.
var snapshotter: MGLMapSnapshotter? = MGLMapSnapshotter(options: options)
snapshotter?.start { (snapshot, error) in
if error != nil {
print("Unable to create a map snapshot.")
} else if let snapshot = snapshot {
// Add the map snapshot's image to the image view.
indicator.stopAnimating()
self.imageView.image = snapshot.image
}
snapshotter = nil
}
}
}