Show current user location on SwiftUI Map

110 Views Asked by At

I'm trying to show the current user location on a SwiftUI map. The centre location of the map will be a facility - I'm taking the CLL coordinates of that from an array. What I want is to show the user their own location in relation to the facility, providing they are within the range I've set (highly likely as it's specific to a small town). The code I'm using is:

Map(bounds: MapCameraBounds(minimumDistance: 500, maximumDistance: 3000)) { Marker(facility.facilityName, coordinate: facility.coordinate)

I have tried adding showUserLocation: True to the Map parentheses both before and after the MapCameraBounds parameters, but it doesn't like that. I've tried pulling the code out into a separate variable, but it won't take the facility.coordinate. There are quite a few answers relating to this, but they don't seem to be suing the latest version of Xcode, so I don't think they're helpful - I haven't found that any of them answer my question and get it to work.

1

There are 1 best solutions below

3
Gismay On

The example below passes the coordinates and region information through to a Map, which will zoom to those coordinates and also show the users current location on the map.

struct FirstView: View {
    @State private var markedLocation = CLLocationCoordinate2D(latitude: 51.50546, longitude: 0.07535)
    var body: some View {
        MapView(markedLocation: markedLocation, mapRegion: MKCoordinateRegion(center: markedLocation, latitudinalMeters: 3000, longitudinalMeters: 3000))
    }
}
struct MapView: View {
    @State var markedLocation:CLLocationCoordinate2D
    @State var mapRegion:MKCoordinateRegion
    
    var body: some View {
        Map(initialPosition: .region(mapRegion)) {
            UserAnnotation()
            Marker("Facility name", coordinate: markedLocation)
        }.mapControls {
            MapUserLocationButton()
        }
    }
}