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

Posts under Maps & Location subtopic

Post

Replies

Boosts

Views

Activity

[MapKit] Initialization failed because the authorization token is invalid.
When I try to import mapkitjs using HTML, I use the correct token, but the error token is invalid. <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>地点信息查询</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; margin: 0; padding: 20px; background-color: #f5f5f7; } .container { max-width: 800px; margin: 0 auto; } .search-box { width: 100%; padding: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 8px; font-size: 16px; } .result-container { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .place-image { width: 100%; max-height: 300px; object-fit: cover; border-radius: 8px; margin-bottom: 15px; } .place-info { margin-top: 15px; } .place-info h2 { margin-top: 0; color: #1d1d1f; } .info-item { margin: 10px 0; color: #515154; } #map { width: 100%; height: 300px; border-radius: 8px; margin-top: 20px; } </style> </head> <body> <div class="container"> <h1>地点信息查询</h1> <input type="text" id="searchInput" class="search-box" placeholder="请输入地点名称(如:北京故宫)"> <div class="result-container"> <div id="placeImage"></div> <div class="place-info"> <h2 id="placeName"></h2> <div id="placeDetails"></div> </div> <div id="map"></div> </div> </div> <script src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script> <script> // 初始化 MapKit mapkit.init({ authorizationCallback: function(done) { done('mytoken'); }, language: 'zh-CN', region: 'CN', callback: function(error) { if (error) { console.error('MapKit 初始化错误:', error); alert('地图服务初始化失败,请检查网络连接和授权设置'); } else { console.log('MapKit 初始化成功'); } } }); // 添加错误处理 window.addEventListener('error', function(event) { console.error('MapKit 错误:', event.error); }); const searchInput = document.getElementById('searchInput'); const placeImage = document.getElementById('placeImage'); const placeName = document.getElementById('placeName'); const placeDetails = document.getElementById('placeDetails'); const mapDiv = document.getElementById('map'); let map; searchInput.addEventListener('input', debounce(searchPlace, 500)); function debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } async function searchPlace() { console.log('搜索'); const query = searchInput.value; if (!query) return; try { // 使用 MapKit 搜索地点 const search = new mapkit.Search({ region: new mapkit.CoordinateRegion( new mapkit.Coordinate(39.9042, 116.4074), // 默认北京坐标 new mapkit.CoordinateSpan(0.1, 0.1) ) }); search.search(query, (error, data) => { if (error) { console.error('搜索错误:', error); return; } if (data.places.length > 0) { const place = data.places[0]; displayPlaceInfo(place); showMap(place); } }); } catch (error) { console.error('获取地点信息失败:', error); } } function displayPlaceInfo(place) { placeName.textContent = place.name; let detailsHTML = ''; if (place.address) { detailsHTML += `<p class="info-item">地址: ${place.address}</p>`; } if (place.phoneNumber) { detailsHTML += `<p class="info-item">电话: ${place.phoneNumber}</p>`; } if (place.url) { detailsHTML += `<p class="info-item">网址: <a href="${place.url}" target="_blank">${place.url}</a></p>`; } placeDetails.innerHTML = detailsHTML; // 获取地点图片 if (place.pointOfInterestCategory) { // 这里可以调用其他图片API来获取地点图片 // 示例使用占位图片 placeImage.innerHTML = `<img src="https://source.unsplash.com/800x400/?${encodeURIComponent(place.name)}" class="place-image" alt="${place.name}">`; } } function showMap(place) { if (map) { map.remove(); } map = new mapkit.Map(mapDiv, { region: new mapkit.CoordinateRegion( place.coordinate, new mapkit.CoordinateSpan(0.01, 0.01) ) }); const annotation = new mapkit.MarkerAnnotation(place.coordinate, { title: place.name, data: { place: place } }); map.addAnnotation(annotation); } </script> </body> </html>
1
0
83
Apr ’25
[CoreLocation][iOS 18.3.2] OS is not notifying monitored region state to application
We have an application. We are monitoring the fence event. We are using 'startMonitoringForRegion' API. but we are not getting any fence event. Steps Create a fence using 'startMonitoringForRegion' API BG on APNS trigger. initial fence state 'didDetermineState' not received. From Syslogs we can see OS has detected but event is not given to Application We are compiling code using SDK18.0 Error ** locationd Fence: LAC monitoring is not sufficient for / ocationd Fence: no allowing wifi monitor for, 400.0, fence Feedback Ticket ID: FB17250308 Syslogs Snippet: debug 2025-04-15 12:45:40.890193 -0500 locationd FenceCal: combine non-fine non-large fence, distance, 0.0, / //OS detetected fence state default 2025-04-15 12:45:44.706232 -0500 locationd Fence: fenceUpdate, , bundle, , type, GPS , loc, 33.1171776, -96.6606076, acc, 19, distance, 17, tech, LC...+, trans, 0, state, 0, cont, 1, fence, 33.11728835, -96.66048288, 1011.0, 766431742.6, sCount, 0, 0, trig, 0, 3, sinceLastLoc, 10.0, events, 0x00001810, status, (Inside) => (Inside) , settled state, (Unknown) ==> (Unknown), cantShiftButNeedTo, 0, sinceLastTransition, -1.0, significant, 0, loi, 0, lastProximityStateTimestamp, -1.000000, lastProximityState, 0, lastApproachingState, 0 // debug 2025-04-15 12:45:44.706247 -0500 locationd Fence: LAC monitoring is not sufficient for / // debug 2025-04-15 12:45:44.706263 -0500 locationd Fence: no allowing wifi monitor for, 400.0, fence, Fence, []//, latitude, 33.11728835, longitude, -96.66048288, refFrame, 0, distance, 1011.0, eFistance, 1011.0, lDown, -1.0, time, 766431742.6, ctime, -1.0, flags, EX------, key, -1506186373, throttled, N, polygon, 0, envType, 2, locType, 0
1
0
126
Apr ’25
Core Location reports incorrect location update especially with underground travel
Description of the Bug: Core Location intermittently reports inaccurate location updates, albeit with a high accuracy value. This problem occurs almost exclusively while travelling in metros underground affecting the ability to rely on the framework effectively. Steps to Reproduce: The user starts travelling on ground level at point A The user continues travelling and, after some time, is now underground at point B. A stationary beacon scanned at point B confirms this. Core Location is observed to deliver a location update with a high-accuracy value but with the coordinates around point A when the user is actually around point B. Expected Behaviour: Accurate locations should be delivered at all times. In other words, Core Location should not report location updates with high accuracy when its certainty is low.
1
0
59
Apr ’25
Zspeedaccuracy question
Hello everyone, I'm doing some work on validating some data to do with the zpseed functionality around corelocations, i've read up on the speedaccuracy field but the wording doesn't make sense to me. It says if its a positive number it is plus or minus the value in the zspeed column so would this be for example zspeed of 35 mps with an accuracy of 3 mps would it be 32 mps 38 mps or is it a range? so would it be anywhere between 32-38 mps. Or is it just plus or minus the 3mps and if this is the case how would it be worked out if its plus or minus when all the numbers will be a positive numbers as any negative numbers are deemed inaccurate ?
1
0
54
Apr ’25
Unable to use altitude for our use case (NYC MTA)
We’re building a new subway/bus app at the MTA. Our system includes roughly 300 underground stations, around 150 elevated stations (i.e., above street level), and about 5 at-grade stations (i.e., at street level). We serve roughly 5 million riders a day. We’re diving deep into Core Location on iOS and have found that the altitude values returned from two fields we’re testing aren’t accurate enough for our use case: CLLocation.altitude CMAbsoluteAltitudeData.altitude We need to reliably distinguish whether a user is: At street level On an elevated platform (see attached picture) On any platform in an underground station — most have a single platform level, but some, like 59 St (see attached), have multiple platforms at different elevations. These levels typically differ by at least 15 feet, which should in theory be well within the precision range of a properly calibrated barometric pressure sensor. However, the absolute altitude values we’re seeing from these APIs are often inaccurate and inconsistent — not only compared to ground truth, but also across devices. For example, holding two phones side-by-side frequently yields altitude readings that differ by more than 15 feet. That level of variation makes the data unreliable for our needs. Please see the below photos for more context. URLs.md
8
0
146
Apr ’25
UIKit mapView color annotations
I have tried to make colored annotations in mapView (shown in the commented sections) but they always appear in black. Any help would be appreciated. func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "TempAnnotationView") annotationView.canShowCallout = true annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) let configuration = UIImage.SymbolConfiguration(pointSize: 10, weight: .thin, scale: .default) if annotation.title == "Start" { // let config = UIImage.SymbolConfiguration.preferringMulticolor() // let image = UIImage(systemName: "flag.fill", withConfiguration: config) // // palette // let config2 = UIImage.SymbolConfiguration(paletteColors: [.systemRed, .systemGreen, .systemBlue]) // let image2 = UIImage(systemName: "person.3.sequence.fill", withConfiguration: config2) // // hierarchical symbols // let config3 = UIImage.SymbolConfiguration(hierarchicalColor: .systemIndigo) // let image3 = UIImage(systemName: "square.stack.3d.down.right.fill", withConfiguration: config3) // // color // let image4 = UIImage(systemName: "cone.fill")?.withTintColor(.systemRed, renderingMode: .alwaysTemplate) // annotationView.image = image4 annotationView.image = UIImage(systemName: "poweron", withConfiguration: configuration) } return annotationView }
3
0
705
Apr ’25
Localisation on Apple Watch
Hi everyone! I’m a new developer diving into my first Apple Watch project, and I’m really excited to get started! This app relies heavily on using the most precise location data possible. Could anyone point me to some official documentation or helpful resources on how to achieve high-accuracy location tracking specifically for watchOS? Any tips or best practices would also be greatly appreciated! Thanks in advance for your help!
1
0
64
Apr ’25
Issue with calculating the distance between two points on a map
I have an error issue that I haven’t been able to solve despite doing extensive research. In fact the similar examples I have found so far have been educational but I have not been able to make work. The example below I am hoping will be easy to fix as it is only producing errors with one line of code… import SwiftUI import CoreLocation var currentLon = Double() var currentLat = Double() extension CLLocation { class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance { let from = CLLocation(latitude: from.latitude, longitude: from.longitude) let to = CLLocation(latitude: to.latitude, longitude: to.longitude) return from.distance(from: to) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLon = (locations.last?.coordinate.longitude)! currentLat = (locations.last?.coordinate.latitude)! }/*⚠️ Not sure if this function will work? (Update User Location coordinates on the move?)*/ } struct Positions: Identifiable { let id = UUID() let name: String let latitude: Double let longitude: Double var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } struct GameMapView: View { let from = CLLocationCoordinate2D(latitude: currentLon, longitude: currentLat) let to = CLLocationCoordinate2D(latitude: thisCardPositionLongitude, longitude: thisCardPositionLongitude) let distanceFrom = from.distance(from: to) /*⚠️ ERRORS: 1. Cannot use instance member 'from' within property initializer; property initializers run before 'self' is available. 2. Cannot use instance member 'to' within property initializer; property initializers run before 'self' is available. 3. Value of type 'CLLocationCoordinate2D' has no member 'distance'. */ @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D( latitude: thisCardPositionLatitude, longitude: thisCardPositionLongitude), span: MKCoordinateSpan( latitudeDelta: 0.0001, longitudeDelta: 0.0001) ) var body: some View { Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: locations){ place in MapMarker(coordinate: place.coordinate,tint: Color.accentColor) } .edgesIgnoringSafeArea(.all) VStack { Print("Distance from Location: \(distanceFrom)") font(.largeTitle) padding() }
1
0
100
Apr ’25
Specify location for SwiftUI Previews
I'm working on an app that uses MapKit and CoreLocation. Is there a way to specify what location is simulated for a Preview, or create a preview that behaves as if the user denied location permissions, so that I can easily test my app's behavior in different scenarios? I know that you can simulate different locations in the Simulator, but haven't been able to get the previews within Xcode to have a location other than the center of Apple Park.
0
0
69
Apr ’25
Guidance on Continuous Location & Direction Updates to watchOS App Without Screen Dimming
Dear Apple Developer Support, I am reaching out for guidance on implementing continuous directional and location updates in a watchOS app designed as part of a mapping/navigation solution. Current Scenario: We send continuous location and direction updates from our iOS app to the watchOS companion app. When viewing directions on the Apple Watch, the screen dims after a short period, and the live data stops updating consistently, even though the user is actively looking at the screen. This negatively impacts the usability of real-time navigation on watchOS. Our Objective: Prevent screen dimming (or extend screen-on time) while the user is viewing navigation directions. Ensure reliable, continuous data updates on the watch screen during active navigation sessions. Request: We would appreciate your guidance on: The recommended method to keep the watchOS screen active while displaying real-time navigation data. Proper use of APIs such as WKExtendedRuntimeSession, WorkoutSession, or any other mechanism suitable for this use case. Any best practices or App Store review considerations for apps that require extended screen time and continuous updates. How such use cases were traditionally handled on watchOS and what has or hasn’t worked. We want to ensure we're implementing this in a battery-efficient, user-respectful, and Apple-compliant manner. Thank you for your assistance and guidance.
1
0
63
Apr ’25
Background Modes - App Identifiers
Hey All, Seem to be in a loop and unable to proceed. New app specific for iOS being built on xCode. Project is configured only to deploy and use iOS, not macOS or anything else. Trying to create a new App iD always see it default to all platforms which means "Background Modes" is not visible or available. Automatic signing etc in xcode can't seem to get around this and just continues to flag I'm missing the entitlement for locations.background. Not sure what I am missing as I cannot manually configure the ID for iOS only and xcode is also generating new ID's with the same platform structure and constraints. Any thoughts or insights here please?
5
0
99
Apr ’25
Potential memory leaks in CLLocationUpdate.Updates
This is my first post here. Please guide me, if I need to provide more information to answer this post. I write a simple application, that monitors GPS position (location). I followed Apple documentation for LiveUpdates: https://developer.apple.com/documentation/corelocation/supporting-live-updates-in-swiftui-and-mac-catalyst-apps My app can monitor location in foreground, background or it can completely stop monitoring location. Background location, if needed, is switched on when application changes scenePhase to .background. But it is in the foreground, that memory leaks occur (according to Instruments/Leaks. Namely Leaks points to the instruction: let updates = CLLocationUpdate.liveUpdates() every time I start location and then stop it, by setting updatesStarted to false. Leaks claims there are 5x leaks there: Malloc 32 Bytes 1 0x6000002c1d00 32 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:) CLDispatchSilo 1 0x60000269e700 96 Bytes CoreLocation 0x184525c64 Malloc 48 Bytes 1 0x600000c8f2d0 48 Bytes Foundation +[NSString stringWithUTF8String:] NSMutableSet 1 0x6000002c4240 32 Bytes LocationSupport 0x18baa65d4 dispatch_queue_t (serial) 1 0x600002c69c80 128 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:) I tried [weak self] in Task, but it doesn't solve the leaks problem and causes other issues, so I dropped it. Anyway, Apple doesn't use it either. Just in case this is my function, which has been slightly changed comparing to Apple example, to suit my needs: func startLocationUpdates() { Task() { do { self.updatesStarted = true let updates = CLLocationUpdate.liveUpdates() for try await update in updates { // End location updates by breaking out of the loop. if !self.updatesStarted { self.location = nil self.mapLocation = nil self.track.removeAll() break } if let loc = update.location { let locationCoordinate = loc.coordinate let location2D = CLLocationCoordinate2D(latitude: locationCoordinate.latitude, longitude: locationCoordinate.longitude) self.location = location2D if self.isAnchor { if #available(iOS 18.0, *) { if !update.stationary { self.track.append(location2D) } } else { // Fallback on earlier versions if !update.isStationary { self.track.append(location2D) } } } } } } catch { // } return } } Can anyone help me locating these leaks?
4
0
559
Apr ’25
Using Maps in App Intents
I want to use MapKit with App Intents, but the map does not show up.(See attached image) Can anyone help me solve this? import SwiftUI import MapKit struct ContentView: View {   @State private var region = MKCoordinateRegion(     center: CLLocationCoordinate2D(latitude: 37.334_900,                     longitude: -122.009_020),     latitudinalMeters: 750,     longitudinalMeters: 750   )       var body: some View {     VStack {       Map(coordinateRegion: $region).frame(width:300, height:300)         .disabled(true)     }   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } import AppIntents import SwiftUI import MapKit struct test20220727bAppIntentsExtension: AppIntent {   static var title: LocalizedStringResource = "test20220727bAppIntentsExtension"       func perform() async throws -> some IntentResult {     return .result(value: "aaa", view: ContentView())   } } struct testShortcuts:AppShortcutsProvider{   @available(iOS 16.0, *)   static var appShortcuts: [AppShortcut]{     AppShortcut(       intent: test20220727bAppIntentsExtension(),       phrases: ["test20220727bAppIntentsExtension" ]     )   } }
2
0
1.2k
Mar ’25
App Clips Advanced Experiences not showing up in Apple Maps and Siri Suggestions
Hello everyone, I’m experiencing an issue with App Clips Advanced Experiences and Apple Maps/Siri Suggestions. We have already contacted Apple Support before, but they are investigating the cause of this issue and it has not been resolved til date. The App Clip is bundled with the main app and has been already available on the App Store for several months. The business running the app has several physical shops and wants to offer the App Clip to show up in Apple Maps and Siri Suggestions at each location. The App Clip is correctly exposed in the AASA file, and it's also validated correctly by the AASA APIs available at https://app-site-association.cdn-apple.com/a/v1. { "applinks": { "apps": [], "details": [ { "appID": "TEAMID.bundleid", "paths": [] } ] }, "appclips": { "apps": [ "TEAMID.bundleid.Clip" ] } } (with TEAMID and bundleid being the team and bundle identifiers of the app) The App Clip is displayed correctly when loading the website and when scanning a QR code or App Clip code, but doesn't appear in the Maps app or in Siri suggestions. We have set up the App Clip Advanced Experiences on the App Store Connect page of the app, and each URL has been linked to a physical shop. All URLs are in the "Received" state, so they should appear correctly on Maps. Unfortunately, I don't see any "Order" button in Apple Maps at any location card. We tried with both iOS 17 and 16. According to feedbacks from people in the shops, they don't see the app suggested in the Siri Suggestions. I have just submitted a Custom Action Link on Apple Business Connect for one of the shops, but without success: the App Clip doesn't appear. Any idea why is this happening?
8
1
915
Mar ’25
CarPlay map view stops updating when iPhone screen turns off
Hello all, I have a food delivery app that I am beginning to implement CarPlay support in. Route picking, navigation, turn-by-turn guidance features all work perfectly on iPhone, and on CarPlay while the iPhone is unlocked, or locked but screen on. However, when the iPhone is locked and the screen is off, the CarPlay map view stops following the user's location and appears to be frozen. When this happens, the other "map buttons" that are part of the CPMapTemplate continue to accept user input (I can enter and exit the map panning mode for example), the user's location continues to update, and the turn-by-turn guidance continues as normal. It appears to be just the map view (which is drawn on the window and is not part of the CPMapTemplate) that stops updating in this state. I've been through every page of Apple documentation on CarPlay but nothing references or addresses how to keep the CarPlay session active while the iPhone is locked. I'm not sure where else to look for answers and I'm out of theories as to why this might happen. Any guidance around this would be greatly appreciated.
1
0
86
Mar ’25
Notification Delivery Issues for Location Push Service Extension
We are currently testing the implementation of our Location Push Service Extension (LPSE) in both Ad Hoc and Release environments. We have encountered an issue where LPSE notifications, which were previously working correctly, suddenly fail to be delivered on some devices. After a period of several hours, the notifications resume arriving, but the issue remains intermittent. Notably, during these periods of suspected delivery restriction, regular push notifications (e.g., those using apns-push-type: alert) are delivered and displayed without any problem. [Detailed Situation] Test Environment and Scope We are testing LPSE after obtaining the necessary entitlements, in both Ad Hoc and Release environments. The issue is not observed on all test devices; only certain devices are affected. Observed Behavior Under normal circumstances, LPSE notifications are received and the extension is activated; however, on some devices the notifications suddenly stop arriving. During these periods, even when sending notifications with apns-push-type: location directly via the CloudKit Push Notification Console, no response is observed on the affected devices. The APNs server (api.push.apple.com) always returns a 200 OK response via HTTP/2, and our server-side logs and configurations (DNS resolution performed on every request, using the same JWT token for 59 minutes per session, communication via HTTP/2 with ALPN Protocol: h2) show no issues. Other app functionalities (network communication, UI responsiveness, etc.) work normally. Sending content When sending notifications from our server to APNs (api.push.apple.com), we use the following configuration (over HTTP/2): const payload = { aps: { 'content-available': 1 } }; const headers = { ':method': 'POST', ':path': /3/device/${apnsToken}, 'Authorization': bearer ${jwtToken}, 'apns-topic': 'ot.Here.location-query', 'apns-priority': '10', 'apns-push-type': 'location', 'Content-Type': 'application/json' }; We perform DNS resolution for every request, use the same JWT token for a 59-minute period per session, and communicate via HTTP/2 with ALPN Protocol: h2. Hypothesis on the Cause We suspect that due to an implementation issue, silent push notifications (using content-available: 1) were being sent every few minutes concurrently, which may have triggered an APNs delivery restriction (rate limiting). As a countermeasure, we have completely stopped sending silent pushes and any other background notifications aside from LPSE; however, the issue persists. Additionally, even after resetting affected devices, the delivery problem continues to occur. [Questions for Diagnosis] Given the above situation, is it reasonable to suspect that excessive silent push notifications have triggered an APNs delivery restriction? Does such a silent push restriction affect LPSE notifications (i.e., those sent with apns-push-type: location)? Do APNs delivery restrictions persist even after a device has been reset? Can a high volume of LPSE notifications alone (without silent pushes) also trigger a delivery restriction? → This is our primary concern since it poses a significant implementation challenge. Please let us know if any additional information is required for diagnosis.
3
0
86
Mar ’25