Maps & Location

RSS for tag

Learn how to integrate MapKit and Core Location to unlock the power of location-based features in your app.

Maps & Location Documentation

Post

Replies

Boosts

Views

Activity

MapView mapType `.standard` iOS17 does not allow 3d
I am working on a virtual simulator for iOS 17 from my macbook. I want to have the initial view present the Map but zoomed out enough so that it's basically showing the whole world - in a 3d render. My understanding is that as of iOS17 if you have .standard for the MKMapView type, it should still render as 3D if the altitude is high enough. But on my simulator, I literally cannot zoom out any further. Is the right protocol to update the mapType to be .hybridFlyover? That seems different than the .standard (which I think is what I actually want). Does anyone have any idea / is there anything sticking out in this code? Here is my code: struct GlobeView: UIViewRepresentable { var coordinates: [IdentifiableCoordinate] func makeUIView(context: Context) -> MKMapView { let mapView = MKMapView() mapView.mapType = .hybridFlyover mapView.delegate = context.coordinator let camera = MKMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 0, longitude: 0), fromDistance: 1_000_000_000, pitch: 0, heading: 0) mapView.setCamera(camera, animated: true) return mapView } func updateUIView(_ uiView: MKMapView, context: Context) { let annotations = coordinates.map { coordinate -> MKPointAnnotation in let annotation = MKPointAnnotation() annotation.coordinate = coordinate.coordinate return annotation } uiView.addAnnotations(annotations) } class Coordinator: NSObject, MKMapViewDelegate { var parent: GlobeView init(_ parent: GlobeView) { self.parent = parent } } func makeCoordinator() -> Coordinator { Coordinator(self) } }
1
0
352
Jan ’24
Does CLMonitor work in simulator?
When I run CLMonitor in the simulator, event state remains at default. Although when running the same project on device, state does correctly change between satisfied and unsatisfied. In the simulator I did allow location updates when in use as I did on device. This occurs with the Apple sample code, Monitoring location changes with Core Location associated with the WWDC 2023 session Meet Core Location Monitor. Am I misusing simulator and/or CLMonitor?
1
0
393
Oct ’23
Asking Location Permission is not working on the AppIntents
@MainActor perform() async throws -> some IntentResult { // ... switch locationManager.authorizationStatus { case .denied, .restricted: throw UserLocationError.permissionDenied case .notDetermined: await locationManager.requestWhenInUseAuthorization() // to ask permission default: break } // ... } Here is my code. When the authorizationStatus is .notDetermined, it invokes requestWhenInUseAuthorization() method on the main thread, but throws UserLocationError.permissionDenied immediately, eventhough I didn't deny the permission. It's really weird and unexpected that it throws UserLocationError.permissionDenied when the status is not .denied or .restricted Even it invokes requestWhenInUseAuthorization(), there's no alert for asking permission If there's any solution, please let me know
0
0
369
Jan ’24
Region monitoring not working after 1 hour the app is killed.
This is my setup: Granted always allow permission. I have location added in UIBackgroundModes, but I did NOT set allowsBackgroundLocationUpdates to true Note: I have this allowsBackgroundLocationUpdates = true set in my earlier version of app, which worked but we noticed it drained battery much faster, hence we removed all the settings that could affect battery. The location model is setup with 20 regions, when boundary crossing happen, app sends a local notification. This works fine when app is in foreground/background. If app is killed, the app receives notification for boundary crossing only once. Failed case for region monitoring: Setup region monitoring Kill the app cross the boundary, app sends a local notification. wait for 1 hour leave the device in same state (notification is not opened, app is still killed state) cross the boundary again expect a notification, but app did not register any event related to region monitoring. The console logs did not print anything in this second case. public class LocationViewModel: NSObject, ObservableObject { private let maxMonitoredRegions = 20 private var anyCancellable: AnyCancellable? private let locationManager: CLLocationManager @Published public var authorizationStatus: CLAuthorizationStatus @Published public var isMonitoringAvailable: Bool @Published public var monitoredRegions: [Region] @Published public var recentLocation: CLLocation? public var newlyEnteredRegionSignal = PassthroughSubject<CLRegion, Never>() public var recentLocationSignal = PassthroughSubject<CLLocation, Never>() public var authorizationStatusPublisher: Published<CLAuthorizationStatus>.Publisher { $authorizationStatus } public var isLocationEnabled: Bool { locationManager.authorizationStatus == .authorizedWhenInUse || locationManager.authorizationStatus == .authorizedAlways } public override init() { locationManager = CLLocationManager() authorizationStatus = locationManager.authorizationStatus isMonitoringAvailable = CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) monitoredRegions = [] super.init() locationManager.delegate = self monitoredRegions.append(contentsOf: getMonitoredRegions()) requestLocation() } public func requestLocation() { locationManager.requestLocation() } public func startRegionMonitoring(regions: [CLRegion]) { guard isMonitoringAvailable else { return } stopRegionMonitoring() if regions.isEmpty { return } if regions.count <= 20 { for region in regions { locationManager.startMonitoring(for: region) } } else { for region in regions[0...maxMonitoredRegions-1] { locationManager.startMonitoring(for: region) } } } public func stopRegionMonitoring() { guard isMonitoringAvailable else { return } if monitoredRegions.isEmpty { return } for region in monitoredRegions { let monitoredRegion = LocationUtils.convertRegionToCLRegion(region) locationManager.stopMonitoring(for: monitoredRegion) } monitoredRegions.removeAll() } private func getMonitoredRegions() -> [Region] { let monitoredRegions = locationManager.monitoredRegions var regions = [Region]() for monitoredRegion in monitoredRegions { if let region = LocationUtils.convertCLRegionToRegion(monitoredRegion) { regions.append(region) } } return regions } public func stopMonitoring() { recentLocation = nil stopRegionMonitoring() } } extension LocationViewModel: CLLocationManagerDelegate { public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus switch authorizationStatus { case .notDetermined: stopMonitoring() case .denied: stopMonitoring() case .authorizedAlways: break case .authorizedWhenInUse: // If user has requested whenInUse, request for always allow. locationManager.requestAlwaysAuthorization() @unknown default: break } if let location = manager.location { recentLocationSignal.send(location) recentLocation = location } } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let recentLocation = locations.last { self.recentLocation = recentLocation recentLocationSignal.send(recentLocation) } } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { } public func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { if let monitoredRegion = LocationUtils.convertCLRegionToRegion(region) { let oldRegion = monitoredRegions.first { $0.identifier == monitoredRegion.identifier } if oldRegion == nil { monitoredRegions.append(monitoredRegion) } } } public func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { } public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { newlyEnteredRegionSignal.send(region) } public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { newlyEnteredRegionSignal.send(region) } } When app is awaken due to location event on app delegate, we initialize this location model, and location manager, and remove old monitored regions, and call startMonitoringRegions again, to keep the regions updated. Please let me know if I'm missing any crucial information.
1
1
352
Jan ’24
Searching for an example of a proper iBeacon implementation for iOS 17
Hello, I'm looking for an end-to-end example project that shows a correct implementation for the new iBeacon CoreLocation APIs in iOS 17.0 (CLMonitor, etc.). Ideally the example would cover background waking as that is the area in which I am facing the largest challenges. Perhaps there's an Open Source project or an official Apple example? Thanks for pointing me in the right direction. Jeremy
3
0
718
Jan ’24
How to select MapFeature by custom type
If have a custom type (hashable) for map selection: @State var mapSelection: CustomType Map(selection: $mapSelection ) { ... } However, if I want to selet MapFeature, I need to use MapFeature type for the state variable @State var mapSelection: MapFeature But I want to display some Markers by using my CustomType. MapFeature can't be initialized so that I can't map my CustomType to MapFeature to display my Markers. Is there a way to select MapFeature by custom type?
1
0
310
Jan ’24
Is it free to use MapKit's MKLocalSearchCompleter and MKLocalSearch on iOS currently?
Is it free to use MapKit's MKLocalSearchCompleter and MKLocalSearch on iOS currently? I would like to use them for getting geocode. I found this forum. https://developer.apple.com/forums/thread/127493 According to this forum, using MapKit for native app development, there is no cost beyond my Apple Developer Program membership. Is it the same now? sincerely
0
0
381
Jan ’24
MapKit UI - Marker / Protocol help
Hi , I'm trying to teach myself the new Mapkit code. Can someone help me fix the code below: I'm getting the following error on Line 19: Initializer 'init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)' requires that 'Marker' conform to 'MapAnnotationProtocol' import MapKit struct IdentifiableAnnotation: Identifiable { let id = UUID() var annotation: MKPointAnnotation } struct ContentView: View { @ObservedObject var locationManager: LocationManager @State private var showUserProfile = false @State private var showNotifications = false @State private var showFriendz = false @State private var courtAnnotations: [IdentifiableAnnotation] = [] var body: some View { NavigationView { ZStack(alignment: .bottom) { Map(coordinateRegion: $locationManager.region, interactionModes: .all, showsUserLocation: true, userTrackingMode: .none, annotationItems: courtAnnotations) { item in Marker(<#LocalizedStringKey#>, coordinate: item.annotation.coordinate) } .edgesIgnoringSafeArea(.all)
2
1
460
Nov ’23
Maps searchAutoComplete response field "structuredAddress" always null
Regardless of how much information is provided to the Maps searchAutoComplete API, the response field structuredAddress is always null. This means I have to call the completionUrl afterwards to get a structured address. This consumes our quota and causes unnecessary Maps traffic. Example request, autocompleting "450 Post St, San Francisco": https://maps-api.apple.com/v1/searchAutocomplete? q=450%20Post%20St%2C%20San%20Francisco &resultTypeFilter=Address &limitToCountries=US &lang=en-US responds 2 results with the actual address found, but each having only these fields: - completionUrl - displayLines - location Example: { "results": [ { "completionUrl": "/v1/search?q=450%20Post%20St%20San%20Francisco%2C%20CA%2C%20United%20States&metadata=Ch8KCzQ1MCBQb3N0IFN0EgQIABADEgQIBBAEEgQICRACEjQKIFNhbiBGcmFuY2lzY28sIENBLCBVbml0ZWQgU3RhdGVzEgQIGhACEgQIABADEgQIBBAJGAIyRgoSCQAAAEDg5EJAEQAAAOA9ml7AEM6h0aK1wfKqciA5KQAAAAAAAHlAgvEEAzQ1MIjxBDGa8QQCVVOg8QQAsvEEALrxBABiHAoaNDUwIFBvc3QgU3QsIFNhbiBGcmFuY2lzY2%2BC8QQaNDUwIFBvc3QgU3QsIFNhbiBGcmFuY2lzY2%2BI8QQA2vEEFgkAAABAEf3IQBkAAAAAAAAAACABKAPq8QQAkPIEAQ%3D%3D", "displayLines": [ "450 Post St", "San Francisco, CA, United States" ], "location": { "latitude": 37.78809356689453, "longitude": -122.41002655029297 } }, { "completionUrl": "/v1/search?q=450%20Post%20St%20Napa%2C%20CA%2C%20United%20States&metadata=****", "displayLines": [ "450 Post St", "Napa, CA, United States" ], "location": { "latitude": 38.30093002319336, "longitude": -122.27799224853516 } } ] } Anyone figured this out? Seems buggy to me.
0
2
497
Jan ’24
Map In TabView
In SwitUI when using a map within a tabview the tab bar color is translucent when the map tab is selected. All of the other tabs the tab bar is opaque. In the view that contains the map, if the map is commented out the tab display is opaque, only when the map is displayed. I have an init in the tabview to set the tab bar parameters: // Set Tab Bar appearance let tabbarAppearance = UITabBarAppearance() tabbarAppearance.configureWithOpaqueBackground() tabbarAppearance.backgroundColor = .blue UITabBar.appearance().standardAppearance = tabbarAppearance UITabBar.appearance().scrollEdgeAppearance = tabbarAppearance In the view with the map I use a ZStack to set the entire screen color: ZStack(alignment: Alignment(horizontal: .center, vertical: .top)) { Color(.blue) .ignoresSafeArea(.all) .foregroundColor(.black) VStack(alignment: .center, spacing: 5) { Spacer() Map() Spacer() } } I've tried using .padding(), frame, removing ignoresSafeArea but the tab bar still becomes translucent when the tab is selected. Selecting another tab the color becomes opaque. Any suggestions on how to correct this behavior so the tab bar is opaque for all tabs?
0
0
358
Jan ’24
App store alert to download Apple maps appears twice
I have a code that redirects the user to Google Maps or Apple Maps by pressing the map , when Apple Maps is uninstalled, an alert appears asking the user to download Apple Maps and redirects the user to the App Store, when I select Show in App Store, the user is redirected to App Store, and then the alert is shown again. func openMaps() { let coordinate = CLLocationCoordinate2D(latitude: 52.5162746, longitude: 13.3755153) let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate)) mapItem.name = "Test" mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault]) }
0
0
253
Dec ’23
How to increase the nmea logging period
Hi experts, I got an Ultra2 a while ago and has been using it on walking / running exercise. Recently I came across to this apple site: debug profile and I'm curious about what I would get during the exercise. So I follow the instruction and install the location services profile. After getting the sysdiagnose report, I try to get location related information from it. And it seems that the log from "locationd" and "gpsd" are what I'm looking for. But when I try to look into the nmea information, I found out the sysdiagnose only provide around 10-15 mins of nmea data. For example, let's say I have a walking exercise from 0900 - 1000, but I can only see nmea data from 0945 - 1000. The data from 0900 to 0945 can't be found in the sysdiagnose. Not sure if's the limitation or any setting I can change to increase the logging period? Thanks.
0
0
440
Dec ’23
iOS 17.1 Location Update not terminated When In Use
I activate the conditions as follows Unexpected operation found. Details are below Conditions and configurations used in the testing "Background Modes" Capability with "Location updates" checked on added the info.plist keys: NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription with description monitoring for several beacon regions and invoking startMonitoringSignificantLocationChanges using core location API My app’s location authorization status set ‘WhenInUse’ add UserNotification in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool. For that reason, If every app launches, a notification will be triggered in AppDelegate method Given the condition above applied, What I expect is that if the location permission is 'when in use', if I leave the app by swiping(I have not closed my application by force using "swiping up in the app-switcher screen"), the app will be suspended in the background after 30 seconds. However, on specific iOS(iOS 16.5.1~ iOS 17.1.2), when I bring the app to the background, the didUpdateLocation function continues to run. I confirmed that the location was updated for over an hour. Other iOS didn’t occur the issue under iOS 16.3.1.(Couldn't confirm 16.4) I wonder if this is normal operation. In addition, I also want to know why it is working differently between iOS versions. Thanks for your help in advance.
0
0
289
Dec ’23
MapKit billing policy on native apps
Thank you all in advance. I've checked the terms and the pre-posted forum related to the same question. https://developer.apple.com/forums/thread/127493 I have plans to use MapSDK in my native app and is critical to know that it really is free to use. Though I've checked the answers, I was wondering if there's a written document that says it's free to use on native apps.
1
0
283
Dec ’23
[Support/Advise plz] High LocationAccuracy in Background but Low/Minimum in Terminated - possible?
Hello Community, Need your help/guidance please. Seeking LocationServices experts who can advise me whether my idea for a valuable add-on feature that I've been trying to add into my app for 2+ months is achievable or not given LocationServices limitations. The Feature: to enable users who would like to be automatically notified whenever they're within X meters from a store that provides them an exclusive discount BUT only when they choose to be notified. Instruction to enjoy the feature is by keeping app open in 'background state' (means opened and kept in background) but not when app is terminated state (completely closed). The state is important because I would like to give users the choice to only receive notifications when they choose to instead of all-time. That is to eliminate unnecessary power consumption fetching location updates constantly when user don't need them (example staying at home, at work, etc), but give them option when they go out. Ideal scenario (after opting in to enable 'Always'): user launches the app, keeps in background, go out shopping/dining/etc and enjoy convenience of being automatically notified whenever about Xmeters from a place that they have an exclusive offer for. Implemented conditions: API is called at fixed time interval whenever user is within about 10 meters from their last location, that is to limit checking only when there is certainty user is within the same place for sometime instead of just walking by (this currently works perfectly, using AccuracyBest), the challenge when user terminates app, LocationServices wakes up again and continues to fetch location updates constantly. The Ask: Is it technically possible that I configure app LocationServices to not wake-up with [AccuracyBest] when terminated but instead use only reduced accuracy (like 'significant location updates' or on 'AccuracyOne/ThreeKilometer')? Ideas/suggestions/recommendations would be much much appreciated
0
0
484
Dec ’23
Geolocation tracking for IOS apps using .net Maui
I'm working on an in-house iOS app designed to help users accurately track their routes during trips. Currently, I've implemented a method to track users when the app is open in the background. However, I'm facing challenges, as the tracking stops when the device is locked for more than 10 minutes. I'm looking for a solution to continuously track a user's geolocation, even if the app is closed or not in use. Specifically, I want to ensure uninterrupted tracking, especially when the device is locked. Here are some key points: Current Method: I'm currently using the Core Location method and a combination of background tasks and a repeating timer to fetch the user's location and update a log for geolocation tracking when the app is open in the background. Issues Faced: The tracking stops when the device is locked for more than 10 minutes. This limitation impacts the accuracy of the route tracking during longer trips. Objective: My goal is to achieve continuous geolocation tracking, even when the app is closed or not actively used, to provide users with a seamless and accurate record of their routes. Platform: The app is developed for iOS using the .net maui platform, and I'm seeking solutions or suggestions that are compatible with the iOS .net maui environment. If anyone has experience or insights into achieving continuous geolocation tracking on iOS, especially when the app is not in use or the device is locked, I would greatly appreciate the assistance.
0
1
609
Dec ’23