使用自訂檢視畫面建立標記

您可以使用 Marker,在 3D Map 上將自訂 SwiftUI View 階層算繪為標記。自訂檢視區塊標記可讓您顯示豐富的 SwiftUI 版面配置、互動式控制項,以及錨定在地理座標上的動畫。

新增自訂檢視區塊標記

如要在 Map 中加入自訂檢視區塊標記,請在地圖內容建構工具中宣告 Marker,使用 LatLngAltitude 值指定其 position,並在結尾的 content 閉包中提供自訂 SwiftUI View。

如果省略 content 閉包,Marker 會算繪預設的 Pin 檢視畫面。

import GoogleMaps3D
import SwiftUI

struct CustomMarkerExampleView: View {
  var body: some View {
    Map(mode: .hybrid) {
      Marker(
        position: LatLngAltitude(
          latitude: 40.7484,
          longitude: -73.9857,
          altitude: 100.0
        ),
        altitudeMode: .relativeToGround
      ) {
        Text("Empire State Building")
          .padding(.horizontal, 12)
          .padding(.vertical, 6)
          .background(Color.white)
          .clipShape(Capsule())
      }
    }
  }
}

自訂預設圖釘檢視畫面

您不必建構完全自訂的 SwiftUI View,只要將使用 Pin.Configuration 初始化的 Pin 傳遞至 Marker 內容閉包,即可算繪自訂圖釘:

import GoogleMaps3D
import SwiftUI

struct CustomPinMarkerExampleView: View {
  var body: some View {
    Map(mode: .hybrid) {
      Marker(
        position: LatLngAltitude(
          latitude: 40.7484,
          longitude: -73.9857,
          altitude: 100.0
        ),
        altitudeMode: .relativeToGround
      ) {
        Pin(
          configuration: .init(
            backgroundColor: .blue,
            borderColor: .white
          )
        )
      }
    }
  }
}

處理互動和動畫

由於 Marker 託管 SwiftUI View,您可以將標準 SwiftUI 手勢修飾符 (例如 .onTapGesture) 和 SwiftUI 動畫,直接附加至 Marker 內容閉包內的檢視畫面。

此外,Marker 符合 MapContentAnchorable,可讓您使用 popover(isOpen:autoClosedEnabled:autoPanEnabled:style:content:) 修飾符將 Popover 錨定至標記:

import GoogleMaps3D
import SwiftUI

struct InteractiveMarkerExampleView: View {
  @State private var isPopoverOpen = false

  var body: some View {
    Map(mode: .hybrid) {
      Marker(
        position: LatLngAltitude(
          latitude: 37.7955,
          longitude: -122.3937,
          altitude: 0
        ),
        altitudeMode: .relativeToGround
      ) {
        Pin(configuration: .init(backgroundColor: .black) {
          Image(systemName: "ferry.fill")
            .foregroundStyle(.white)
        })
        .onTapGesture {
          isPopoverOpen.toggle()
        }
      }
      .popover(isOpen: $isPopoverOpen) {
        Text("Ferry Building")
      }
    }
  }
}

設定高度和衝突行為

您可以將參數傳遞至 Marker.init,自訂 Marker 的垂直位置,以及與重疊地圖標籤或標記互動的方式: