如何使用 MapKit (SwiftUI) 将工具提示添加到地图注释以便在地图上显示位置名称

How to add tooltip to Map Annotation in order to show the location name on the Map using MapKit (SwiftUI)

我正在尝试弄清楚如何在将鼠标悬停在 Annotation/Marker 上或仅点击 annotation/Marker 时显示 MapAnnotation 的 title/name。有没有简单的方法可以做到这一点?

我尝试使用 .help(),但它没有在地图上显示任何内容...

这里是相关代码...

  Map(coordinateRegion: $viewModel.region, showsUserLocation: true, annotationItems: viewModel.locations){ location in
    MapAnnotation(coordinate: location.coordinate) {

    Image(systemName: "mappin.circle")
    .help("\(location.name)")

  }
}

您没有向地图注释添加工具提示。您制作自己的自定义视图。您可以根据需要显示它,并根据需要显示和隐藏子视图。例如:

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
}