Display map or satellite imagery from your app's interface, call out points of interest, and determine placemark information for map coordinates using MapKit.

Posts under MapKit tag

138 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

How to correct business location?
My organization, Los Angeles Pierce College, rents space to "Topanga Vintage Market", which is a monthly weekend swap meet operation. Apple Maps shows the location as roughly 34.18715° N, 118.58058° W. However, this is the location of the campus Child Development Center, which provides child care services and is not open during the hours of the Topanga Vintage Market. The actual location should be in the adjacent large parking lot, roughly 34.18740° N, 118.57782° W. They do not have a physical building. How do I get this resolved? I am putting a campus mapping application into the App Store real soon now. There is also an entry for "ALC Taco Truck" about 34.18533° N, 118.57349° W, which as far as I know has not been on campus since Covid. Thanks in advance for any guidance you can provide.
1
0
152
1w
How can you determine if the map tiles in MapKit have successfully loaded?
We are developers of a golf app designed to assist golfers on the course. A key feature of our app is displaying a map of each hole, and we are currently transitioning to using MapKit and camera functionalities for this purpose. However, we are encountering issues with the downloading of map tiles when using the default satellite imagery. We have tried several approaches to diagnose the issue: We have tried several things to diagnose the issue: We implemented the mapViewDidFailLoadingMap delegate method. But it is inconsistent, sometimes triggering offline errors even when map tiles are cached. We implemented, the mapViewDidFinishRenderingMap method, but it always returns false when offline or you won't get the callback. Which doesn't let us know that rendering tiles has failed. We would appreciate your guidance on the following specific questions: Does MapKit provide a way to confirm if a map tile has fully loaded? Is there a method to detect if a portion of the map hasn't loaded or if a tile request has failed? Can we determine whether a map tile is cached, and if so, how long it will remain cached, similar to Cache-Control HTTP headers? Is there a way to trigger the preloading of map tiles when we know the user has a good internet connection? Please see the sample project for steps to reproduce the issue. Thank you for any assistance!
2
0
101
1w
Warnings - Failed to locate resource
I have a test application I'm working on (so it's a fresh Xcode project under Sonoma - with older map code borrowed from another project). It is a macOS application. And in Obj-C. When the map window is opened the logs contain the following - I've been trying to hunt down and resolve. Thank you in advance for any clues/pointers. Failed to locate resource "default.csv" Failed to locate resource "satellite@2x.styl" Failed to locate resource "satellite@2x.styl" Failed to locate resource "satellite.styl" Failed to locate resource "satellite@2x.styl" Failed to locate resource "satellite@2x.styl" Failed to locate resource "satellite.styl" Failed to locate resource "satellite.styl" Couldn't find satellite.styl in framework, file name satellite.styl Authorization status: Authorized The application does have MapKit.framework included.
3
1
362
3w
Unexpected Frame Resizing Behavior During Animation of safeAreaInset content.
Hey everyone! I’m encountering an issue while attempting to animate height changes of the content inside safeAreaInset(edge:alignment:spacing:content:). When animating a reduction in the frame height, the container view (in my case, Map) also animates unexpectedly. However, when animating an increase in the frame height, the animation works smoothly, and the Map view remains still. How can I address this odd resizing behavior of the container? Code: struct MapView: View { var body: some View { Map() .safeAreaInset(edge: .bottom) { MapDetailView() } } } struct MapDetailView: View { @State private var oldHeightOffset: CGFloat = 0 @State private var newHeightOffset: CGFloat = 0 @State private var containerHeight: CGFloat = 0 private var drag: some Gesture { DragGesture(coordinateSpace: .global) .onChanged { value in withAnimation(.interactiveSpring) { newHeightOffset = oldHeightOffset + value.translation.height } } .onEnded { value in switch newHeightOffset { case containerHeight * 0.625...containerHeight: withAnimation(.spring) { newHeightOffset = containerHeight * 0.75 } case containerHeight * 0.25..<containerHeight * 0.625: withAnimation(.spring) { newHeightOffset = containerHeight * 0.5 } case 0..<containerHeight * 0.25: withAnimation(.spring) { newHeightOffset = 0 } default: break } oldHeightOffset = newHeightOffset } } var body: some View { NavigationStack { Rectangle() .fill(.clear) .containerBackground(.ultraThinMaterial, for: .navigation) } .gesture(drag) .containerRelativeFrame(.vertical) { length, _ in length - newHeightOffset } .onGeometryChange(for: CGFloat.self) { geometryProxy in let frame = geometryProxy.frame(in: .local) return frame.height + newHeightOffset } action: { containerHeight in self.containerHeight = containerHeight } } } Reducing safe area inset's content height (drag down): Increasing safe area inset's content height (drag up):
2
0
216
1w
Need clarification on using Apple MapKit in CarPlay
I have developed a mobile app using SwiftUI that supports GoogleMaps. Now I am in the process of building a CarPlay application. I assume CarPlay only supports Apple MapKit, as I could not find any way to integrate the Google Maps. Below are few queries, Could you please guide me on how I can obtain the user's current location on the CarPlay app launch? Is there a way CarPlay can get the details from the mobile app(not pretty sure as its using Google Maps)? If the user is logged out from the mobile app, what is the flow in CarPlay? Do we have any standard login page asking user to login to the mobile app first? Is there any UI asking the user to capture the location in CarPlay? This is my first CarPlay app. Kindly guide me to a document or so that covers these details. Thanks a ton!!
1
0
247
2w
Changing MKMapView .preferredConfiguration or .mapType causes crash
If I change MKMapView's .preferredConfiguration property from .realistic to .flat, or .mapType from .hybridFlyover to .hybrid, subsequent scrolling causes a crash: -[MTLDebugRenderCommandEncoder validateDrawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:function:]:6179: failed assertion `Draw Indexed Primitives Validation indexBufferOffset(0) + (indexCount(864) * 2) must be <= [indexBuffer length] (12). For example, changing: mapView.preferredConfiguration = MKHybridMapConfiguration(elevationStyle: .realistic) to: mapView.preferredConfiguration = MKHybridMapConfiguration(elevationStyle: .flat) Then, scroll the map view, and it will crash. It is OK the other way around. Or change: self.mapView.mapType = .hybridFlyover to: self.mapView.mapType = .hybrid I've tried everything I can think of, including calling functions like these after the change: mapView.setNeedsDisplay() mapView.setRegion(self.mapView.region, animated: false) .mapType and .preferredConfiguration are settable properties, so they should be possible to change. I could create a new MKMapview, but I'd have to perfectly recreate the state which is not trivial and far from ideal. I'm just trying to work around the issue FB14553276 so my map tiles don't show tiling seems in 2D which is a new issue introduced with iOS 18. This potential workaround still shows the seems in 3D, but is better than always showing seems. Seems like whatever I do, I just can't defeat MapKit bugs and puts me in an impossible situation. :( I've submitted Feedback this issue: FB16153802 It seems like others are experiencing the issue: https://forums.developer.apple.com/forums/thread/730780
0
0
234
Dec ’24
How to search location in global rather than in local?
I'm doing a weather app, users can search locations for getting weather, but the problem is, the results only shows locations in my country, not in global. For example, I'm in China, I can't search New York, it just shows nothing. Here's my code: @Observable class SearchPlaceManager: NSObject { var searchText: String = "" let searchCompleter = MKLocalSearchCompleter() var searchResults: [MKLocalSearchCompletion] = [] override init() { super.init() searchCompleter.resultTypes = .address searchCompleter.delegate = self } @MainActor func seachLocation() { if !searchText.isEmpty { searchCompleter.queryFragment = searchText } } } extension SearchPlaceManager: MKLocalSearchCompleterDelegate { func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { withAnimation { self.searchResults = completer.results } } } Also, I've tried to set searchCompleter.region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 0, longitude: 0), span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 360) ), but it doesn't work.
2
0
405
Dec ’24
Separate RealityView inside a RealityView attachment
Hi, I am having some troubles creating a "nested" RealityView content using MapKit attachment. I am building a visionOS app that has horizontal MapKit map as an attachment to RealityView. I want to display 3D pins on that map, therefore I am using native map annotation and inside of these annotations, I create a new RealityView just for the 3D pin. This worked completely fine, unitil I wanted to have those RealityViews interact with each other. By interaction of those RealityViews I mean that I wanted to group entities from the first "main" RealityViews content with the 3D pins using ModelSortGroupComponent. Why I want this? I want to make the map circular, that is not a problem. Problem is that when I move the map with 3D pins, these pins have their own RealityView space and are only bounded by volumetric window dimensions. What happes is that these pins float next to the map (shown on attached image). So I came up with this solution: create a custom "toroid" like 3D entity model that occludes the pins that go outside the map region. In order to occlude only the pins, I need to use ModelSortGroupComponent to group the "toroid" entity with 3D pins entities (as described in another forum thread). To summarize: need the content of the superior RealityView to interact with map attachment annotations RealityView content in order to group them. There might be of course another, better way to achieve my whole goal, so I would naturally appreciate any help or guidance. Image below showing 3D pins on circular map. Since pins RealityView does no know anything about other RealityViews, it just overlows and hangs in space until is cropped by volumetric window boundary. Simplified code: var body: some View { let modelSortGroup = ModelSortGroup(depthPass: .prePass) RealityView { content, attachments in var mainEntity = Entity() // My other entities here... if let mapAttachment = attachments.entity(for: "mapAttachment") { // Edit map properties, position, horizontal layout etc. mainEntity.addChild(mapAttachment) } // Create and add to content mask "toroid" entity mapMaskEntity. Use OcclusionMaterial() material. mapMaskEntity.components.set(ModelSortGroupComponent(group: modelSortGroup, order: 0)) // For all pins, somehow also set the group // 3DPinEntity.components.set(ModelSortGroupComponent(group: modelSortGroup, order: 1)) content.add(mainEntity) } attachments: { Attachment(id: "mapAttachment") { Map { ForEach(mapViewModel.clusters, id: \.id) { cluster in Annotation("", coordinate: cluster.coordinate) { MapPin3DView(cluster: cluster) } } } .clipShape(Circle()) } } } // MapPin3DView is an map annotation view that includes a model of 3D pin and some details like image etc., uses RealityView. struct MapPin3DView: View { var body: some View { RealityView { content in // 3D pin entities... } } }
1
0
211
Dec ’24
Is MapKit.mapCameraKeyframeAnimator broken on macOS 15.2?
Hi! I'm attempting to run the Quakes Sample App^1 from macOS. I am running breakpoints and confirming the mapCameraKeyframeAnimator is being called: .mapCameraKeyframeAnimator(trigger: selectedId) { initialCamera in let start = initialCamera.centerCoordinate let end = quakes[selectedId]?.location.coordinate ?? start let travelDistance = start.distance(to: end) let duration = max(min(travelDistance / 30, 5), 1) let finalAltitude = travelDistance > 20 ? 3_000_000 : min(initialCamera.distance, 3_000_000) let middleAltitude = finalAltitude * max(min(travelDistance / 5, 1.5), 1) KeyframeTrack(\MapCamera.centerCoordinate) { CubicKeyframe(end, duration: duration) } KeyframeTrack(\MapCamera.distance) { CubicKeyframe(middleAltitude, duration: duration / 2) CubicKeyframe(finalAltitude, duration: duration / 2) } } But I don't actually see any map animations taking place when that selection changes. Running the application from iPhone simulator does show the animations. I am building from Xcode Version 16.2 and macOS 15.2. Are there known issues with this API on macOS?
0
0
127
Dec ’24
MapKit super slow loading tiles stored on device
Loading tile overlays is slow even when the raster data is locally available on the device running iOS 18.2 and built with Xcode 16.2. In this video (https://3dtopo.com/superSlowTileLoading.mov) it takes 38 seconds to load tiles readily available on the device. Then, the whole screen flashes when tiles that are already drawn are redrawn, making for a very poor user experience. 38 seconds to load a dozen or so small images (512x512) stored locally on the device is simply unacceptable. I can't release a product like this that I've spent the last 1.5 years building and many years developing the maps themselves. This severe issue is new since I committed to basing my app on MapKit. Note that this issue does not occur with Apple's base map tiles. I created a Feedback Assitant case, FB16110803, for this issue. For the video, I disabled loading any tiles from the network and disabled loading any other data, such as polylines. Essentially all I am doing is loading the tiles stored on the device and returning them, such as: public func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -> Void) { fetchData(forKey: key, failure: {error in result(nil, error)}, success: {data in result(data, nil)}) } open func fetchData(forKey key: String, failure fail: ((Error?) -> ())? = nil, success succeed: @escaping (Data) -> ()) { let path = self.path(forKey: key) do { let data = try Data( contentsOf: URL(fileURLWithPath: path), options: Data.ReadingOptions()) succeed(data) self.updateDiskAccessDate(atPath: path) } catch { if let block = fail { block(error) } } }
6
0
359
Dec ’24
Deriving Apple Place ID from CLPlacemark or MKMapItem
I am trying to derive the Apple Place ID from a CLPlacemark (or via a MKMapItem derived from it) created via either CLGeocoder().reverseGeocodeLocation() or CLGeocoder().geocodeAddressString(). In many cases, the placemark returned from these functions contains detailed information (name, address, coordinates, etc), implying that the Apple Place ID is known, but the identifier is not present. The only way I have found to get a Place ID is via MKLocalSearch. Wondering if I am missing something here.
1
0
230
Dec ’24
How to set the ZPriority of a MapKit Annotation with SwiftUI
Am displaying a number of annotations on a map which vary their location over time and can inherently cluster together. I'd like to be able to set the Z order on the annotations as I have simple logic how to order them in the Z direction. I see the ZPriority property on UIKit Annotation view, but unclear how I can do that in SwiftUI. Is this exposed in any manner? I thought I could create a viewModifier and using the content parameter I'd be able to drop down into the UIKIt view to apply the value to the property, but alas I'm not seeing a clear way to do so. Is this at all possible without dropping down entirely to creating a NSViewRepresentable/UIViewRepresentable implementation of Map?
0
0
173
Dec ’24
iOS 18 MapKit discrepancy between physical devices and simulators
I have noticed a discrepancy between behavior on physical devices and simulators in iOS 18. I am using the latest MapKit APIs to fetch MKMapItems using the following MKLocalSearch: private func performLocalSearch(_ query: String) async throws -> [MKMapItem] { let request = MKLocalSearch.Request() request.naturalLanguageQuery = query let search = MKLocalSearch(request: request) return try await search.start().mapItems } This returns an array of MKMapItem on both the simulator and physical device. The key difference is my physical device (iOS 18.1.1) is missing the MKMapItem's identifier value. On the simulator, identifier is always populated in addition to my search. Any ideas on how to resolve this? The new MapKit API for those curious: @available(iOS 6.0, *) open class MKMapItem : NSObject { @available(iOS 18.0, *) open var identifier: MKMapItem.Identifier? { get }
1
0
301
Nov ’24
Map in SwiftUI just wont follows users heading when first shown
I want to use a Map to show current location and heading, but the map first show, it just wont work. And when I switch off and switch on again, it works. codes below: BackgroundMapView.swift import SwiftUI import MapKit struct BackgroundMapView: View { var scope: Namespace.ID? private var cameraPosition: MapCameraPosition = .userLocation( followsHeading: true, fallback: .automatic ) private var locations: [Location] init(_ scope: Namespace.ID? = nil, locations: [Location]) { self.scope = scope self.locations = locations } var body: some View { Map( initialPosition: cameraPosition, scope: scope ) { MapPolyline(coordinates: locations.map({ $0.coordinate.toGCJ02 })) .stroke( .red, lineWidth: 3 ) } .mapControlVisibility(.hidden) } } #Preview { MainView() } HomeVIew.swift import SwiftUI struct HomeView: View { @StateObject private var locationManager = LocationManager() @State private var isMapEnabled = UserDefaults.isHomeMapEnabled { didSet { UserDefaults.isHomeMapEnabled = isMapEnabled } } @Namespace private var mapScope var body: some View { if isMapEnabled { BackgroundMapView(mapScope, locations: locationManager.locations) .mapScope(mapScope) } } }
1
0
206
Nov ’24
Horizontal window/map on visionOS
Hi, would anyone be so kind and try to guide me, which technologies, Kits, APIs, approaches etc. are useful for creating a horizontal window with map (preferrably MapKit) on visionOS using SwiftUI? I was hoping to achieve scenario: User can walk around and interact with horizontal map window and also interact with (3D) pins on the map. Similar thing was done by SAP in their "SAP Analytics Cloud" app (second image from top). Since I am complete beginner in this area, I was looking for a clean, simple solution. I need to know, if AR/RealityKit is necessary or is this achievable only using native SwiftUI? I tried using just Map() with .rotation3DEffect() which actually makes the map horizontal, but gestures on the map are out of sync and I really dont know, if this approach is valid or complete rubbish. Any feedback appreciated.
2
0
279
Nov ’24
MapKit - render a line above everything, including annotations
I have a map application that needs to show a line (representing a direct route) that is above everything, including annotations. This is important because the map has lots of annotations (possibly hundreds) and the line is representing a route from point to another. With that many annotations being on top the line / route is basically useless because you can't see it. I've looked at things like MKOverlayLevel but it only supports .aboveRoads or .aboveLabels. Is there a way to set the z-axis of a map overlay so that it truly is on top of everything else on the map, including annotations? And if not directly in MapKit, what other options might I have? Worth noting that I'm targeting 16.4 and above, so that's my limitation on this
1
0
257
Dec ’24
SwiftUI Color Issue
I have ran into an issue that is illustrated by the code in the following GitHub repository. https://github.com/dougholland/ColorTest When a SwiftUI color originates from the ColorPicker it can be persisted correctly and renders the same as the original color. When the color originates from the MapFeature.backgroundColor, it is always rendered with the light appearance version of the color and not the dark appearance version. The readme in the GitHub repo has screenshots that show this. Any assistance would be greatly appreciated as this is affecting an app that is in development and I'd like to resolve this before the app is released. If this is caused by a framework bug, any possible workaround would be greatly appreciated also. I suspect it maybe a framework issue, possibly with some code related to the MapFeature.backgroundColor, because the issue does not occur when the color originates from the ColorPicker.
2
1
345
Dec ’24
How the duck can I use .p8 to get the Mapkit Server API token to use it without 7 day duration?
https://developer.apple.com/documentation/applemapsserverapi/creating-and-using-tokens-with-maps-server-api This doesn't really say what to do with .p8 private key. I know I am a noob but I really don't understand Apple Doc at all. There is no example or anything like that. const appleMapKit = await fetch("https://maps-api.apple.com/v1/token", { headers: { Authorization: `Bearer ${server_api_token}`, }, }); This is what I did but because I created the token on website, server_api_token only lasts 7 days. So, I tried to use Profile - Key to replace that. I have .p8 file and how can I use this to create the token for the server api?
1
0
303
Nov ’24
MapCameraPosition & userLocation
I have a Map within a SwiftUI. I initialize a variable like this: var cameraPosition: MapCameraPosition = .userLocation(followsHeading: true, fallback: .automatic) and then I want to zoom map, code like this: let userRegion = MKCoordinateRegion( center: userLocation.coordinate, span: MKCoordinateSpan( latitudeDelta: 0.01, longitudeDelta: 0.01 ) ) cameraPosition = .region(userRegion) But it does't work. How can I solve this problem?
0
1
230
Nov ’24
MapSelection of MapFeatures and MKMapItems
I have a Map within a SwiftUI app that has the selection parameter set to an optional MapSelection. I need to be able to select MapFeatures which works as expected as well as MKMapItems which are added to the map. The MKMapItems are not selectable. Is it possible to make it such that the Map allows the user to select MKMapItems as well as MapFeatures?
1
0
298
Nov ’24