在结构 MapView 上显示用户位置

Show users location on a struct MapView

我想在 MapView 的结构视图上显示用户位置。目前,地图是通过显示从 API.

中获取的地点来实现的

现在我想添加用户位置。它是在结构中完成的,因此它可以作为 tabItem 调用。

大多数教程都在 class 中展示了实现。有没有一种简单的方法可以将用户位置添加到这个结构中?

import MapKit
import SwiftUI
import CoreLocation

    
    struct MapView: View{
        @EnvironmentObject var places: Places
        @State var placesAPI = [Place]()
        @State var region = MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: 51.3704, longitude: 6.1724),
            span: MKCoordinateSpan(latitudeDelta: 5, longitudeDelta: 5)
        )

        var body: some View {
            Map(coordinateRegion: $region, annotationItems: places) {
                places in
                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude:  places.latitude, longitude: places.longitude)) {
                    NavigationLink(destination: DiscoverView(place: places)) {
                        Image(places.city)
                            .resizable()
                            .cornerRadius(10)
                            .frame(width: 40, height: 20)
                            .shadow(radius: 3)
                    }
                }

            }
            .navigationTitle("Locations")
            .onAppear(){
                apiCallPlaces().getPlaces{(places) in
                    self.places = places
                }

            }
        }
    }

    struct MapView_Previews: PreviewProvider {
        static var previews: some View {
            MapView()
        }
    }

如果您只需要显示它,只需为 Map

使用不同的构造函数

https://developer.apple.com/documentation/mapkit/map

init(coordinateRegion: Binding<MKCoordinateRegion>, interactionModes: MapInteractionModes, showsUserLocation: Bool, userTrackingMode: Binding<MapUserTrackingMode>?)

showsUserLocation 设置为 true 将在适当的权限下达到目的。