0
1

【SwiftUI】マップ上に範囲を表す円を表示する(iOS17)

Last updated at Posted at 2023-11-29

はじめに

昨日に引き続きiOS17で大型アップデートの入ったMapKitに関する記事です。

今回はタップした位置に範囲を表す円を表示してみます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-11-29 at 21.07.52.gif

実装

import SwiftUI
import MapKit

struct ContentView: View {
    // 東京駅の座標
    @State private var position: MapCameraPosition = .region(.init(
        center: .init(latitude: 35.681236, longitude: 139.767125),
        span: .init(latitudeDelta: 0.005, longitudeDelta: 0.005)
    ))

    // マップ上の円の位置
    @State private var mapCircleLocation: CLLocationCoordinate2D = .init()

    var body: some View {
        MapReader { mapProxy in
            Map(position: $position) {
                MapCircle(center: mapCircleLocation, radius: 100)
                    .foregroundStyle(.green.opacity(0.5))
            }
            .onTapGesture { location in
                guard let selectedLocation = mapProxy.convert(location, from: .local) else { return }
                mapCircleLocation = selectedLocation
            }
        }
    }
}

解説

円を表示している箇所はMapCircleです。
centerが円の表示する位置です。今回はタップした位置をcenterに渡しています。
radiusは円の大きさです。

MapCircle(center: mapCircleLocation, radius: 100)

foregroundStyleで円の色を変更する事ができます。

MapCircle(center: mapCircleLocation, radius: 100)
+   .foregroundStyle(.green.opacity(0.5))

円に枠線を付けたい時はstrokeを使用します。

MapCircle(center: mapCircleLocation, radius: 100)
    .foregroundStyle(.green.opacity(0.5))
    .stroke(.black, style: .init(lineWidth: 3))

スクリーンショット 2023-11-29 21.13.39.png

おわり

ほぼUIKitを使わずにマップを使えるようになりました。

公式ドキュメント

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1