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

SwiftUI iOS 17, Xcode 15.3 MapContentBuilder
I consistently get an error that the Map initailizer I'm using is deprecated and I should use a MapContent builder instead. Various errors such as "'MapAnnotation' was deprecated in iOS 17.0: Use Annotation along with Map initializers that take a MapContentBuilder instead." or "'init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)' was deprecated in iOS 17.0: Use Map initializers that take a MapContentBuilder instead." The problem in my code seems to be located here: import SwiftUI import MapKit struct ContentView: View { @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5) ) @State private var restaurants: [Restaurant] = [] var body: some View { Map(coordinateRegion: $region, annotationItems: restaurants) { restaurant in // This uses the updated Annotation API MapAnnotation(coordinate: restaurant.coordinate) { VStack { Text(restaurant.restaurantName) .bold() .foregroundColor(.white) .padding(5) .background(Color.black.opacity(0.75)) .cornerRadius(10) .fixedSize() Image(systemName: "mappin.circle.fill") .foregroundColor(.red) .font(.title) } } The errors persistently occur in the lines immediately below var body: some View { I've been stuck on this for two days now. Any help would be greatly appreciated.
1
1
955
May ’24
ReverseGeocode works badly (returns nonsense)
Users of my app are complaining about incorrect GPS location decoding. I found that the bug is in the reverseGeocode, because it returns nonsensical results. Example: The user is located in Oberhausen, Deutschland at coordinates 51.482015, 6.887064. ReverseGeocode decodes the coordinates as "Oberhausen bei Kirn". It is mistaken 250 km! ReverseGeocode works like this: 51.48, 6.88 - Oberhausen (OK) 51.482, 6.887 - Oberhausen bei Kirn (Error) 51.48, 6.89 - Oberhausen (OK) Test result: If the coordinate precision is greater than 2 decimal places, the reverseGeocode does not work properly. From what the user told me, more apps behave like this. Probably all that work with precise coordinates.
1
0
458
May ’24
2D or 3D indoor mapping app in iOS
Hello! I want to create an indoor mapping application in Swift, using the LiDAR scanner. I searched among frameworks and I found that ARKit, RealityKit and RoomPlan would be useful. Which is the proper way to create a 2D indoor mapping app? And which is the proper way to create a 3D indoor mapping app? Are there any modifications I have to make on my code in order to have both?
1
0
676
May ’24
Questions about Live Activities
Our app is a time reporting service with various functions around that. The user checks in at work, checks out when they go home. We thought it'd be useful to provide a live activity to show how long they have worked for. There is also a couple of other cool things we could do that users would love, but i couldn't find definitive answers to the questions below. 1. We have a geofence-based function that checks the user in when they for example arrive at work, and check them out when they go home, so that they don't have to open the app. However, this means that we will need to start and end the live activity from within a geofence trigger. Is this possible? 2. It seems that the maximum time for a live activity is 8 hours? Sometimes people work for longer... How would we solve this? i would be fine with 12 since it would solve most cases. Is it possible somehow to go beyond 8 hours up to 12? If not, is there a callback that "8 hours are up!" so that i could do a final update on the live activity from a counter to "you started working at 09:04" 3. I have seen that some live activities have buttons. It would be neat if the user can check out via a button on the live activity. However, since we take location and call our servers when checking out, we need to be able to use both the locationmanager and make a network call from the live activity. Is this possible? Thanks in advance, Cheers
0
0
648
May ’24
Inquiry About Using Find My Network for Third-Party App Development
Hello everyone, I hope you’re all doing well. I have a question regarding the use of Apple's Find My network. I’m in the early stages of developing an app that would track third-party Find My-compatible tags. Before proceeding further, I want to ensure that I am compliant with Apple’s guidelines and policies. Can anyone provide insight into whether Apple allows developers to use the Find My crowd-sourced network for their own apps? Specifically, I'm interested in tracking third-party Find My tags through my app. Any guidance or resources you can share would be greatly appreciated! Thank you!
1
0
688
May ’24
Apple Maps cannot route to Latitude & Longitude
I've started getting reports of this today and I am able to replicate it on my end but looking to see if anyone else can verify or if it's possibly regional to me (Canada). In Apple Maps (iOS or macOS), if you search a latitude and longitude -- for example: "49.110,-112.110" and search, it centers on the location as it always has and shows the "Directions" button. When you tap the directions button, I get "A route can't be shown because of a problem connecting to the server.". Alternatively, if you pass the coordinate in via Apple Maps URL (https://maps.apple.com/?daddr=49.110,-112.110) it will route but the route is no longer to those specific coordinates, Apple Maps alters them to some nearest known entity (in this case, the RM of Warner County). If you compare the suggested route end destination with the search results for specifically entering the coordinates, you will see they are different locations and mapping routes are not actually taking you to the coordinates anymore. In the last photo attached, the arrow points to where "49.110,-112.110" is actually located which tapping the "Directions" button cannot figure out a route because of a server issue. If you pass it in via URL, it changes the destination coordinates and begins a route quite a ways away from the intended coordinate. The problem started happening either this morning or last night. Can anyone else confirm this happens to them? Thanks, Mike
14
3
2.1k
May ’24
API Key for MapKit not working for Delphi/TMS
I have generated a key for MapKit and it gave me a private key (p8), a Key ID and a MapKit JS key. I am trying to use MapKit in Delphi TMS FNC Maps but it does not seem to render the maps. The same code works with Google Map Key, but not Apple MapKit. I was told to use the MapKit JS key in TMS by the vendor, but neither the Key ID or the MapKit JS key worked. Any help on this is greatly appreciated. Thank you
1
0
679
May ’24
Flickering after removing MapKit MapPolygons/Polylines
I'm using MapKit for SwiftUI and having an issue when conditionally rendering MapPolygons or MapPolylines. Removing these overlays after a previous render causes them to flicker sporadically in their previous location when a user zooms or moves the camera. The relevant code is as follows: Map(position: $cameraPosition, scope: mapScope) { MapPolygon(coordinates: selectedTileVertices) .stroke( Color(red: 1.0, green: 1.0, blue: 1.0, opacity: isTileSelected ? 1.0 : 0.0), style: StrokeStyle(lineWidth: 5, lineJoin: .round)) .foregroundStyle(selectedTile.color.opacity(0.0)) } A polygon is rendered around a coordinate that a user selects. Upon selecting a new coordinate, a new polygon should render and the old be completely removed from the map. In practice, the new polygon is rendered and the old initially removed, but upon zooming the old polygon flickers in and out of appearance. At some zoom levels the old polygon is completely visible again. The crux of the problem sees to be that I am using .mapStyle(.imagery(elevation: .realistic)). Upon switching to .hybrid all flickering behavior is gone. The flickering becomes worse when doing a lot of zooming/camera movement while the old polygon is rendered and then swapping to a new polygon, and is largely nonexistent if swapping to a new polygon at the same zoom level. I imagine this has something to do with the extra rendering optimizations for satellite imagery. Any help resolving this issue would be appreciated.
1
0
511
May ’24
MKLocalSearch missing Music Venues from response
I have created an MKLocalSearch request as follows: let reqVenue = MKLocalSearch.Request() reqVenue.naturalLanguageQuery = "Music Venue" reqVenue.resultTypes = .pointOfInterest reqVenue.region = .init(center: mockCoord, latitudinalMeters: 150, longitudinalMeters: 150) I have made sure mockCoord is the exact location coordinate of the example music venue I want to get back in the response. I have noticed that all Music Venues I can find on Apple Maps do not come back as results in MKLocalSearch. I would love an explanation as to why and what I can do to make them appear in MKLocalSearch results please! best, nick
2
0
508
Jun ’24
Periodic background location polling for infrequently used app
My team and I would like to develop a mechanism that collects the user’s location a few times per day, to detect when the user travels to a different country, for the user’s convenience. The app is very likely going to be opened very rarely. The user would of course be made aware of why collecting the location a few times a day is desired - namely, saving them the effort of having to remember to open the app every time they travel. My question is the following: given that the app would rarely be interacted with, what is the best strategy for collecting the location? The goal is to handle scenarios where the OS might avoid sending location events or notifications to the app. I imagine that the backend might need to intervene and send the occasional push notification to remind the user to open the app from time to time. There are 3 strategies that I’m aware of: LocationManager’s startMonitoringSignificantLocationChanges Scheduling BGAppRefreshTasks Using silent push notifications scheduled by the server. Ideally, using a location push service extension Keeping in mind the “Background execution demystified” WWDC session, documentation, and other threads, I concluded the following: The first idea is probably the least suitable, since it probably requires the app to be opened often, and the location updates would not be sent by OS if the app has been terminated from the app switcher. The second approach would also suffer from infrequent use and termination. The third approach seems not to be affected as much by infrequent usage. I understand that the 3rd strategy might also lead to the OS omitting to wake up the app when it has been terminated by the user. How would you implement this mechanism?
2
0
715
Jun ’24
No pop up to ask a user’s location within the app in MacOS
I have a map tool app in MacOS which needs request Location permission to show MapUserLocationButton. During development, the request for permission can pop up for the first run in my mac, but when it comes to the Apple review(Submission ID: 11f52f82-1d54-481a-9eed-880521fda2b3), they never see that. My mac is Macbook air M2 2022, 14.5 (23F79). Of course, enable App Sandbox - Location and fill up the Privacy - Location When in Use Usage Description Code: // // LocationManager.swift // import MapKit @Observable class LocationManager: NSObject { static let shared = LocationManager() private let manager = CLLocationManager() var isReady: Bool = false var showingAlert = false // var location: CLLocationCoordinate2D? var isAuthorized: Bool { #if os(macOS) .authorized == manager.authorizationStatus #else .authorizedWhenInUse == manager.authorizationStatus #endif } private override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest setup() } private func setup() { isReady = isAuthorized #if os(macOS) if CLLocationManager.locationServicesEnabled() { checkStatus() } else { showingAlert = true } #else checkStatus() #endif } private func checkStatus() { switch manager.authorizationStatus { case .notDetermined: manager.startUpdatingLocation() #if os(macOS) #else manager.requestWhenInUseAuthorization() #endif #if os(macOS) case .restricted, .denied: showingAlert = true case .authorizedAlways, .authorizedWhenInUse: manager.startUpdatingLocation() #else // case .authorizedWhenInUse: // manager.requestLocation() #endif default: break } } } extension LocationManager: CLLocationManagerDelegate { func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { isReady = isAuthorized guard isReady else { return } // manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // location = locations.last?.coordinate } }
2
0
655
Jun ’24
Apple Maps Server API invalid JWT token
Hello, I'm truing to use Maps Server API. I have: Created Maps Identifier and a Private Key Used token maker to create a JWT token. I also tried creating JWT token manually. After generating a JWT token I used Maps Server API Playground with my JWT and I can successfully use Maps Server API. The problem is that when I try to use my JWT in either JS code, Postman or curl request, I get "Invalid Token" error. Which is very strange, because I doubled checked everything dozen of times and JWT works in Apple's playground tool. Here's a request example: curl -si -H"Authorization: Bearer <jwt token>" "https://maps-api.apple.com/v1/geocode?q=Apple%20Park%2C%20Cupertino%2C%20CA" My token is valid for 1 year When generating JWT token I left "Domain restriction" field empty.
1
1
775
Jun ’24
Importing json file and displaying POI's in Mapkit using Xcode 15 and swiftUI
Description: I am working on an iOS 17 app using Xcode 15 and SwiftUI. The app involves displaying points of interest (POIs) on a MapView based on user proximity and other factors such as hours of operation. The data for the POIs is stored in a JSON file, which I am trying to import and parse in the project. However, I have encountered several issues: Deprecation Errors: When attempting to use MapAnnotation, I receive deprecation warnings and errors. It seems that MapAnnotation has been deprecated in iOS 17, and I need to use the new Annotation API along with MapContentBuilder. RandomAccessCollection Conformance: Errors related to RandomAccessCollection conformance when using Map with SwiftUI. JSON Import and Parsing: I used Bundle.main.url(forResource: "locations", withExtension: "json") to load the JSON file but faced issues with correctly parsing and mapping the JSON data to my model objects. What I Need: Guidance on how to correctly use the new Annotation API and MapContentBuilder for displaying POIs on a MapView in iOS 17. Best practices for importing and parsing JSON files in SwiftUI, especially for dynamically updating the MapView based on user proximity and other criteria like hours of operation. Any relevant code snippets or examples would be greatly appreciated. Example of What We Tried Model: swift Copy code struct POI: Codable, Identifiable { let id: Int let name: String let latitude: Double let longitude: Double let hours: [String: String] } Loading JSON: swift Copy code func loadPOIs() -> [POI] { guard let url = Bundle.main.url(forResource: "locations", withExtension: "json"), let data = try? Data(contentsOf: url) else { return [] } let decoder = JSONDecoder() return (try? decoder.decode([POI].self, from: data)) ?? [] } Map View: swift Copy code import SwiftUI import MapKit struct ContentView: View { @State private var pois: [POI] = loadPOIs() @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0060), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05) ) var body: some View { Map(coordinateRegion: $region, annotationItems: pois) { poi in MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: poi.latitude, longitude: poi.longitude)) { VStack { Text(poi.name) Circle().fill(Color.red).frame(width: 10, height: 10) } } } } } Issues Encountered: MapAnnotation is deprecated. Errors related to RandomAccessCollection conformance. Any advice or solutions for these issues would be greatly appreciated. Thank you!
1
0
657
Jun ’24
MapKit JS Not Showing Suburb where marker is located
I'm using MapKit JS to plot markers on a Map - so far so good. I've noticed that it doesn't always show the Suburb name for the location of the marker . Here's an example: The marker is located in Hornsby which isn't showing on the map. If I move the market to an adjacent suburb Wahroonga I get the following: Now Wahroonga isn't showing but Hornsby is showing. I'm trying to find if there's a control that determines when the suburb for the marker is shown or not but haven't been able to find anything so far. I would also like to know if I can control the visibility of suburb names at different zoom levels. If you look at this map you can see the names of various suburbs (Bondi, Bondi Beach, North Bondi etc): but when I zoom in one level these all disappear and I cannot easily locate which suburb the market is in: Is there a way to always show the suburb names so users can easily locate themselves on the map in reference to the suburbs that they might not be familiar with?
2
0
474
Jun ’24
CoreLocation compass heading is wrong
We receive a complaint from a user that the compass heading in our paragliding app differs from the heading in Compass app (preinstalled on iOS). During our research, it was found that third-party apps show the wrong compass heading. We get the compass heading according to the documentation (https://developer.apple.com/documentation/corelocation/getting-heading-and-course-information#Get-the-current-heading): func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading) { magneticHeading = heading.magneticHeading trueHeading = heading.trueHeading } The video linked below shows our app and the third-party app getting the compass heading of 270 degrees, and Compass app (preinstalled) getting the compass heading of 30 degrees. https://drive.google.com/file/d/1HPMRWWq1E_bFYZVyCeqB2Fo-AfG4q9J7/view?usp=share_link This problem appears to the user unpredictably and the correct compass heading is shown by Compass app (preinstalled). He has iPhone 15 Pro Max and iOS 17.4.1. The presence of this problem is very critical as it can cause fatal accidents.
4
0
548
Jun ’24
Did the Snapshot API authentication change too?
Previously (and still, according to the documentation) building a Map Snapshot URL required building the URL with all its parameters, and then signing it using your private key. However, the URL created via the "Create a map" tool simply appends the pre-generated token on the end of the URL. And if I build a URL and do the same thing - append the token, but do not create a signature - the snapshot is generated correctly. (Omitting the token leads to a "not authenticated" message). Is this a new, easier way to generate snapshots?
1
1
489
Jun ’24
SwiftUI+MapKit cannot display the globe view on iPhone.
I hope to use SwiftUI and MapKit to achieve the effect of a globe view when zooming out on the map. The code works in Xcode’s simulator and Simulator, but when running on my iPhone, it only zooms out to a flat world map. I haven’t found anyone else encountering the same issue, so I’d like to ask where the problem might be. Below is the simple code: import SwiftUI import MapKit struct GlobalTest: View { var body: some View { Map(position: .constant(.automatic), interactionModes: [.all, .pan, .pitch, .rotate, .zoom]) { } .mapStyle(.hybrid(elevation: .realistic, pointsOfInterest: .including([.park]), showsTraffic: false)) } } #Preview { GlobalTest() } I have also tried setting the camera properties, but it still doesn’t work. My phone is an iPhone 15 Pro Max, running iOS 17.5.1, and I am in mainland China. The Xcode version is the latest. If anyone understands the reason, please let me know. This is very important to me, and I would be very grateful!
1
1
543
Jun ’24