Skip to main content

View Annotation

公式ドキュメントのURL

ポイント

  • Annotation に カスタムの View を表示する

サンプル (UIKit)

swift
import UIKit
import MapboxMaps

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let mapView = MapView(frame: view.bounds)
// スタイルの設定
mapView.mapboxMap.mapStyle = MapStyle(uri: StyleURI(rawValue: "mapbox://styles/mapbox/standard")!)

// カメラの設定
let center = CLLocationCoordinate2D(latitude: 35.6598, longitude: 139.702389)
let cameraOptions = CameraOptions(center: center, zoom: 13, bearing: 0, pitch: 0)
mapView.mapboxMap.setCamera(to: cameraOptions)

mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)

// ★ カスタム View の Annotation
let viewAnnotation = ViewAnnotation(coordinate: center, view: createSampleView(withText: "Hello world!"))
mapView.viewAnnotations.add(viewAnnotation)

}

// View 作成
private func createSampleView(withText text: String) -> UILabel {
let label = UILabel()
label.text = text
label.font = .systemFont(ofSize: 14)
label.numberOfLines = 0
label.textColor = .black
label.backgroundColor = .white
label.textAlignment = .center
return label
}
}

サンプル (SwiftUI)

swift
import SwiftUI
import MapboxMaps

struct MapboxView: View {
var body: some View {
// スタイルの設定
let mapStyle = MapStyle(uri: StyleURI(rawValue: "mapbox://styles/mapbox/standard")!)

// カメラの設定
let center = CLLocationCoordinate2D(latitude: 35.6598, longitude: 139.702389)
let camera = Viewport.camera(center: center, zoom: 13, bearing: 0, pitch: 0)
Map(initialViewport: camera) {
// ★ カスタム View の Annotation
MapViewAnnotation(coordinate: center) {
Text("Hello world!")
.font(.system(size: 14))
.lineLimit(0)
.foregroundColor(.black)
.multilineTextAlignment(.center)
.background(Color.white)
}
// .priority(3)
}
.mapStyle(mapStyle)
.ignoresSafeArea()
}
}

公式ドキュメントから辿れる、他のサンプル

  • anchor 設定
    • ピンの どの位置に View を表示するかの設定
    • 複数設定しておくと、ピン位置によって適切な anchor が選ばれる
    • ピンを端に近づけると動作がわかる
  • Map のタップ位置に annotation を表示するサンプル
    • mapview.gestures.onMapTap.observe { ... }
  • 画面表示領域に追従して annotation 位置を変更するサンプル