如何使用 MapKit (SwiftUI) 将工具提示添加到地图注释以在地图上显示位置名称
Posted
技术标签:
【中文标题】如何使用 MapKit (SwiftUI) 将工具提示添加到地图注释以在地图上显示位置名称【英文标题】:How to add tooltip to Map Annotation in order to show the location name on the Map using MapKit (SwiftUI) 【发布时间】:2021-12-27 18:54:58 【问题描述】:我试图弄清楚当我将鼠标悬停在注释/标记上或简单地点击注释/标记时如何显示 MapAnnotation 的标题/名称。有没有简单的方法来做到这一点?
我尝试使用 .help(),但它没有在地图上显示任何内容...
这里是相关代码...
Map(coordinateRegion: $viewModel.region, showsUserLocation: true, annotationItems: viewModel.locations) location in
MapAnnotation(coordinate: location.coordinate)
Image(systemName: "mappin.circle")
.help("\(location.name)")
【问题讨论】:
【参考方案1】:您不会向地图注释添加工具提示。您制作自己的自定义视图。您可以根据需要显示它,并根据需要显示和隐藏子视图。举个例子:
import SwiftUI
import CoreLocation
import MapKit
struct MapAnnotationsView: View
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.889499, longitude: -77.035230), span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
let placeArray: [Place] = [Place(title: "Washington Monument", coordinate: CLLocationCoordinate2D(latitude: 38.889499, longitude: -77.035230))]
var body: some View
Map(coordinateRegion: $region, annotationItems: placeArray) annotation in
// This makes a generic annotation that takes a View
MapAnnotation(coordinate: annotation.coordinate)
// This is your custom view
AnnotationView(placeName: annotation.title)
struct AnnotationView: View
let placeName: String
@State private var showPlaceName = false
var body: some View
VStack(spacing: 0)
Text(placeName)
.font(.callout)
.padding(5)
.background(Color.white)
.cornerRadius(10)
// Prevents truncation of the Text
.fixedSize(horizontal: true, vertical: false)
// Displays and hides the place name
.opacity(showPlaceName ? 1 : 0)
// You can use whatever you want here. This is a custom annotation marker
// made to look like a standard annotation marker.
Image(systemName: "mappin.circle.fill")
.font(.title)
.foregroundColor(.red)
Image(systemName: "arrowtriangle.down.fill")
.font(.caption)
.foregroundColor(.red)
.offset(x: 0, y: -5)
.onTapGesture
withAnimation(.easeInOut)
showPlaceName.toggle()
struct Place: Identifiable
let id = UUID()
var title: String
var coordinate: CLLocationCoordinate2D
【讨论】:
以上是关于如何使用 MapKit (SwiftUI) 将工具提示添加到地图注释以在地图上显示位置名称的主要内容,如果未能解决你的问题,请参考以下文章
如何在 SwiftUI MapKit 的 updateUIView 中添加“.setRegion”?
你能从 SwiftUI 中的 MapKit 数据库中获取纬度和经度吗