【问题标题】:Show users location on a struct MapView在结构 MapView 上显示用户位置
【发布时间】:2021-06-01 10:29:36
【问题描述】:

我想在 MapView 的结构视图上显示用户位置。目前,地图是通过显示从 API 获取的地点来实现的。

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

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

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()
        }
    }

【问题讨论】:

    标签: swift dictionary struct userlocation


    【解决方案1】:

    如果您只需要显示它,只需为 Map 使用不同的构造函数

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

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

    showsUserLocation 设置为 true 将使用适当的权限来解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      相关资源
      最近更新 更多