swiftdictionarystructuserlocation

Show users location on a struct MapView


I want to show the users location on a struct view of a MapView. Currently, the map is implemented with showing places fetched from an API.

Now I want to add the user location. It is done in a struct so that it can be called as a tabItem.

Most tutorials are showing the implementation in a class. Is there a simple way to add the user location to this struct?

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

Solution

  • If all you need is the to show it just use a different constructor for Map

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

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

    Having showsUserLocation set to true will do the trick with the proper permissions.