エンジニアの渡邉です。
地図機能を持ったアプリを作成するときにMapboxを使用したので、
Mapboxで地図表示する方法を書こうと思います。
1.Mapboxに登録
https://www.mapbox.com/
からユーザ登録を行います。
2.MapboxSDKをプロジェクトに追加
今回はpodを使用して追加します。
Podfileに以下を追加し、pod installを実行
pod 'Mapbox-iOS-SDK' </code>
3.Info.plistにMapbox access tokenを設定
access tokenはユーザのマイページから確認できます。

MGLMapboxAccessTokenに確認したaccess tokenを設定します。
4.Map表示画面の作成
ViewController上にViewを置き、ViewのクラスをMGLMAPViewにします。

5.コード実装
import UIKit import Mapbox class MapViewController: UIViewController, MGLMapViewDelegate { @IBOutlet weak var mapView: MGLMapView! let styleURL = "mapbox://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" // 作成したStyleのURLを設定 override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setupMapView() } // MARK: - MapView func setupMapView() { if let _ = self.mapView.annotations { self.mapView.removeAnnotations((self.mapView.annotations)!) } self.mapView.styleURL = URL(string: self.styleURL) self.mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.mapView.delegate = self // 地図表示設定 self.mapView.setCenter(CLLocationCoordinate2D(latitude: 35.658034, longitude: 139.701647), zoomLevel: 15, animated: false) // MAP上にピンを立てる let location = CLLocationCoordinate2D(latitude: 35.658034, longitude: 139.701647) let annotation = MGLPointAnnotation() annotation.coordinate = location annotation.title = "渋谷駅" self.mapView.addAnnotation(annotation) // 現在位置を表示 self.mapView.showsUserLocation = true } // ピンをタップしたときにViewを表示させるか設定 func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { return true } // ピンをタップしたときに表示されるViewをタップしたときの動作を設定 func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) { print(annotation.title) } }
Styleはユーザのマイページから作成することができます。
StyleでMapの表示カスタマイズもできるので、目的に合わせてカスタムしたMapをアプリで表示できます。
実装した結果の画面がこちらになります。
ちゃんと表示さてれいることが確認できました。
6.まとめ
Mapboxは実装の難易度も高くなく、自分でMapのカスタマイズができる点が良かったと思います。
今回のブログでは記載できませんでしたが、オフラインでもマップ表示が可能なので、
また機会があればブログに書きたいと思います。