|
Hi all, I'm using MapKit in SwiftUI to display a map with the current location of the user. I have this code so far, but the problem is that I have to manually specify the region. So my question is, How can I make the map always center around the current location of the user? I'm not that experienced yet, so I hope you will have some patience with me
|
|
You will need to ask the user's permission to get their location. To get that, you'll need a plist entry with the key "Privacy - Location When In Use Usage Description" and a string that explains why the app needs that information. You will also need a method that gets the user's location, and which updates the region accordingly. That can probably go inside your locationDelegate struct. I think there are several other wires crossed, so to speak. But I'm not sure how to fix them with a single reply. For example, you'll need to tell CLLocationManager that locationDelegate is the delegate. You have correctly added the CLLocationManagerDelegate in the class's declaration, but that is not enough. I am also not sure that the view should own all those location manager properties, but if they do, they need to be @StateObjects at the very least, not @State. I would approach this screen using a different style, so consider my advice with that caveat. I'm still learning as well. |
|
@bobdel Thanks for the anwser, I was able to update my code a bit so the map now always is centered around the current location of the user. But im not sure what this I tried this This is my current code:
|
|
Wow sorry that was unclear, and its something you've taken care of already with this line of code:
That line is three symbols, manager, delegate, and managerDelegate. The manager is an instance of CLLocationManager, delegate is a property inside manager, and managerDelegate is an instance of the class you have doing most of the work (locationDelegate).
CLLocationManager does not conform to the ObservableObject protocol. It does not need to be owned by a SwiftUI object at all. A better approach I think would be to create it inside your locationDelegate class. In locationDelegate, add these two lines of code:
This detangles CLLocationManager from your SwiftUI code somewhat. Is this part of a 100DaysSwiftUI project? Bob |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.