在 swiftUI 2 中向 MapKit 添加 MapMarker
Posted
技术标签:
【中文标题】在 swiftUI 2 中向 MapKit 添加 MapMarker【英文标题】:adding a MapMarker to MapKit in swiftUI 2 【发布时间】:2020-07-20 05:13:31 【问题描述】:我正在尝试使用新的Mapkit SwiftUI view,我可以显示某个区域的地图,但我不知道如何显示Map Marker。
这就是我所拥有的:
import SwiftUI
import MapKit
struct ContentView: View
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var location1 = MapMarker(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), tint: .red)
var body: some View
Map(coordinateRegion: $region, showsUserLocation: true).edgesIgnoringSafeArea(.all)
有人知道如何将location1
添加到地图吗?我找到了this,但我无法让它工作
【问题讨论】:
【参考方案1】:这是一个简单的演示。使用 Xcode 12 / ios 14 测试
import CoreLocation
import MapKit
struct Marker: Identifiable
let id = UUID()
var location: MapMarker
struct DemoView: View
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
let markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), tint: .red))]
var body: some View
Map(coordinateRegion: $region, showsUserLocation: true,
annotationItems: markers) marker in
marker.location
.edgesIgnoringSafeArea(.all)
【讨论】:
【参考方案2】:您可以使用 MapPin() 或 MapMarker(),如下所示:
import SwiftUI
import MapKit
struct Place: Identifiable
let id = UUID()
let name: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
struct MapView: View
let places = [
Place(name: "Position 1", latitude: 31.21, longitude: 120.50),
Place(name: "Position 2", latitude: 31.210205, longitude: 120.52301),
Place(name: "Position 3", latitude: 31.230006, longitude: 120.54002)
]
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 31.21, longitude: 120.50),
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
var body: some View
Map(coordinateRegion: $region, showsUserLocation: false, annotationItems: places) place in
MapPin(coordinate: place.coordinate)
//MapMarker(coordinate: place.coordinate)
【讨论】:
以上是关于在 swiftUI 2 中向 MapKit 添加 MapMarker的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 MapKit (SwiftUI) 将工具提示添加到地图注释以在地图上显示位置名称
在 SwiftUI 中向 TextField/SecureField 添加图像,向占位符文本添加填充
在 SwiftUI 中向 NavigationView 添加搜索栏