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

MapKit Documentation

Posts under MapKit tag

155 Posts
Sort by:
Post not yet marked as solved
0 Replies
289 Views
I am working on an application with a map. I have some data(addresses and specific locations) that I want the map to have a pin on. Is there a way to add my data into the map and how can I go about doing that?
Posted
by KSoto3.
Last updated
.
Post not yet marked as solved
1 Replies
322 Views
I need multiple MKTileOverlays with multiple blendModes. Apparently using an overlay with a different blend causes the layer under to use the same blend mode. For the example below, using a normal blend mode on top of a soft light blend mode causes a normal blend mode to be used instead of soft light. The soft light layer is rendered as expected until the normal layer is displayed starting at zoom level 15. First, I've subclassed MKTileOverlay to add an overlay type so that the correct renderer is provided per overlay. (I know there is a title, but I prefer this) enum OverlayType { case softLight, normal } class TileOverlay: MKTileOverlay { var type: OverlayType = .normal } Then setup layers and renderers in the typical fashion: var softLightRenderer: MKTileOverlayRenderer! var normalRenderer: MKTileOverlayRenderer! private func setupSoftlightRenderer() { let overlay = TileOverlay(urlTemplate: "http://localhost/softlight/{z}/{x}/{y}") overlay.type = .softLight overlay.canReplaceMapContent = false overlay.minimumZ = 9 overlay.maximumZ = 20 mapView.addOverlay(overlay, level: .aboveLabels) softLightRenderer = MKTileOverlayRenderer(tileOverlay: overlay) tileRenderer.blendMode = .softLight } private func setupNormalRenderer() { let overlay = TileOverlay(urlTemplate: "http://localhost/normal/{z}/{x}/{y}") overlay.type = .normal overlay.canReplaceMapContent = false overlay.minimumZ = 15 overlay.maximumZ = 20 mapView.addOverlay(overlay, level: .aboveLabels) normalRenderer = MKTileOverlayRenderer(tileOverlay: overlay) normalRenderer.blendMode = .normal } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let overlay = overlay as? TileOverlay { switch overlay.type { case .softLight: return softLightRenderer case .normal: return normalRenderer } } print("Warning: using unhandled overlay renderer") return blankRenderer } override func viewDidLoad() { ... setupSoftlightRenderer() setupNormalRenderer() } Interestingly, if I put the overlays at two different levels, one .aboveLabels and another .aboveRoads it works as expected. The problem is that limits me to two different overlay blend modes. I really could use more than two. I tried every possible variation of inserting the layers at different indexes and methods, but the only two that seem to work are the .aboveLabels and .aboveRoads. How can I use more than two different blend modes?
Posted
by 3DTOPO.
Last updated
.
Post marked as solved
8 Replies
655 Views
To restrict outgoing connections, I've ensured that the following key in not present in the entitlement file: <key>com.apple.security.network.client</key> <true/> The api calls made using URLSession and WKWebView are restricted as expected, but the same is not the case with MKMapView. The map content and the directions api are able to make outgoing network calls. Please let me know if it's possible to reliably restrict outgoing network connections in a sandboxed app?
Posted
by on-d-go.
Last updated
.
Post not yet marked as solved
0 Replies
315 Views
This post states that attribution is required for MapKit or violates the developer agreement. Can I provide my own attribution if I am displaying my original map content? It seems bizarre to attribute map sources that are not used.
Posted
by 3DTOPO.
Last updated
.
Post marked as solved
1 Replies
319 Views
Hello , I am working on developing an app that shows users details of a location like opening hours, directions, ratings if available sort of like apple maps does but in a different UI and for different reasons. How do i tap into that information in SwiftUI mapkit? See image below for information window you get when you tap an annotation/marker in apple maps:
Posted
by Wedkemail.
Last updated
.
Post not yet marked as solved
2 Replies
348 Views
Hello, I have successfully used the getCoordinates() function provided by Apple Documentation to convert an address to coordinates. I created my own struct for a Pin that includes name, latitude, and longitude as properties. I am able to add Markers to my map using these three properties. My problem is that I'd like to use these Markers to pull up further information, such as lookaround views. To use these API call functions, I need to provide an MKMapItem as an argument to the mapItem parameter. MKLookAroundSceneRequest(mapItem: MKMapItem) I'm having trouble using the MKMapItem documentation to understand how to make my own MKMapItems. If I try using the autocomplete in XCode, I can get this: MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude))) Is it possible to add a name when instantiating a new MKMapItem? From the documentation, it seems like name is a property of MKPlacemark, but I can't get this to work. Should I alter the getCoordinates() function to return the entire placemark instead of just the coordinates? Any guidance would be much appreciated! Thanks!
Posted
by ieung.
Last updated
.
Post not yet marked as solved
0 Replies
283 Views
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) } }
Posted
by jlarkin.
Last updated
.
Post not yet marked as solved
1 Replies
574 Views
I've never used Swift or SwiftUI before, so I went to the apple SwiftUI tutorials page to attempt to learn the language. In the SwiftUI tutorial: Creating and Combining Views, section 5, step 4 it asks me to insert the line Map(initialPosition: .region(region) in the following code block import SwiftUI import MapKit struct MapView: View { var body: some View { /** this line */ Map(initialPosition: .region(region)) } private var region: MKCoordinateRegion { MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868), span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2) ) } } This code block is directly from the tutorial, however, I get an error stating Cannot infer contextual base in reference to member 'region'. From my own research, there exists a function in MapKit called region which converts from MKCoordinateRegion to MapCameraRegion, which seems to be the desired functionality as according to the documentation here initialPosition is supposed to be of type MapCameraRegion. However, it seems I must be calling this function incorrectly. I thought a logical next step would be to insert the line Map(initialPosition: MapKit.region(region)) as that's how many other languages I've worked with operate but that gives the error Module 'MapKit' has no member named 'region'. I also changed the name of my private var region so the function and the variable wouldn't have the same name and that also had no affect. Any ideas? Thanks in advance.
Posted
by thomasbd.
Last updated
.
Post not yet marked as solved
0 Replies
264 Views
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?
Posted
by Banghua.
Last updated
.
Post marked as solved
2 Replies
847 Views
Anyone able to see how to use the new SwiftUI Map and WWDC @Observable concept to dynamically update my SwiftUI Map position and rotation based on the dynamic changes it picks up from my @Observable object. Note the updates are coming through as the Text labels show this. But how to get the Map position referencing the same values and updating them? The "onAppear" approach doesn't seem to work. import SwiftUI import MapKit @Observable final class NewLocationManager : NSObject, CLLocationManagerDelegate { var location: CLLocation? = nil var direction: CLLocationDirection = 0 private let locationManager = CLLocationManager() func startCurrentLocationUpdates() async throws { if locationManager.authorizationStatus == .notDetermined { locationManager.requestWhenInUseAuthorization() } for try await locationUpdate in CLLocationUpdate.liveUpdates() { guard let location = locationUpdate.location else { return } print("NewLocationManager: \(location.coordinate.latitude), \(location.coordinate.longitude)") self.location = location self.direction = self.direction + 1 } } } struct ContentView: View { var locationMgr = NewLocationManager() @State private var mapCamPos: MapCameraPosition = .automatic private let bigBen = CLLocationCoordinate2D(latitude: 51.500685, longitude: -0.124570) var body: some View { ZStack { Map(position: $mapCamPos) .onAppear { // Does NOT work - how to get position/direction updates working to Map (map should be moving/rotating) mapCamPos = .camera(MapCamera( centerCoordinate: self.locationMgr.location?.coordinate ?? bigBen, distance: 800, heading: self.locationMgr.direction )) } VStack (alignment: .leading) { Text("Location from observable: \(locationMgr.location?.description ?? "NIL")") // This works (they get updates regularly) Text("Direction from observable: \(locationMgr.direction)") // This works (they get updates regularly) Spacer() } } .task { try? await locationMgr.startCurrentLocationUpdates() } } } #Preview { ContentView() } Tag: wwdc2023-10043
Posted
by callagga.
Last updated
.
Post not yet marked as solved
3 Replies
1.9k Views
Hi, I'm looking through SwiftUI Map for SwiftUI documentation (including IOS17 Beta) for way to adjust Map() scale, or zoom level, while simultaneously showing user's location and heading, for which I'm doing this @State var position = MapCameraPosition = .userLocation(followsHeading: true, fallback: .automatic) Map(position: $position) It does not appear to be possible so am looking for confirmation. Thanks everyone.
Posted
by macmac72.
Last updated
.
Post not yet marked as solved
0 Replies
201 Views
Does the API: https://maps-api.apple.com/v1/directions currently not support public transportation queries, such as subway routes?
Posted
by levn.
Last updated
.
Post not yet marked as solved
0 Replies
305 Views
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
Posted
by mori-t.
Last updated
.
Post not yet marked as solved
1 Replies
600 Views
Trying to use new Swift @Observable to monitor GPS position within SwiftUI content view. But how do I tie the latest locations to the SwiftUI Map's mapCameraPosition? Well ideally the answer could cover: How to fix this error - So get map tracking along with the User Position, but also How to include facility to turn on/off the map moving to track the user position (which I'll need to do next). So could be tracking, then disable, move map around and have a look at things, then click button to start syncing the mapcameraposition to the GPS location again Refer to error I'm embedded in the code below. import SwiftUI import MapKit @Observable final class NewLocationManager : NSObject, CLLocationManagerDelegate { var location: CLLocation? = nil private let locationManager = CLLocationManager() func startCurrentLocationUpdates() async throws { if locationManager.authorizationStatus == .notDetermined { locationManager.requestWhenInUseAuthorization() } for try await locationUpdate in CLLocationUpdate.liveUpdates() { guard let location = locationUpdate.location else { return } self.location = location } } } struct ContentView: View { var newlocationManager = NewLocationManager() @State private var cameraPosition: MapCameraPosition = .region(MKCoordinateRegion( center: newlocationManager.location?.coordinate ?? <#default value#>, span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25) )) // GET ERROR: Cannot use instance member 'newlocationManager' within property initializer; property initializers run before 'self' is available var body: some View { ZStack { Map(position: $cameraPosition) Text("New location manager: \(newlocationManager.location?.description ?? "NIL" )") // works } .task { try? await newlocationManager.startCurrentLocationUpdates() } } } #Preview { ContentView() }
Posted
by callagga.
Last updated
.
Post not yet marked as solved
2 Replies
378 Views
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)
Posted
by hupr2828.
Last updated
.
Post not yet marked as solved
0 Replies
309 Views
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?
Posted Last updated
.
Post marked as solved
1 Replies
438 Views
I want to generate randomised MKLookAroundScene for my world exploration app (think geogussr functionality). How can i achieve that with MapKit? I have tried struct LookAroundView: View { @State private var lookAroundScene: MKLookAroundScene? @State private var yOffset: CGFloat = 0 func generateRandomCoordinate() { let minLatitude = -90.0 let maxLatitude = 90.0 let minLongitude = -180.0 let maxLongitude = 180.0 let randomCoordinate = CLLocationCoordinate2D( latitude: Double.random(in: minLatitude...maxLatitude), longitude: Double.random(in: minLongitude...maxLongitude) ) checkLookAroundAvailability(coordinate: randomCoordinate) } func checkLookAroundAvailability(coordinate: CLLocationCoordinate2D) { Task { let request = MKLookAroundSceneRequest(coordinate: coordinate) if let scene = try? await request.scene { DispatchQueue.main.async { self.lookAroundScene = scene } } else { generateRandomCoordinate() } } } var body: some View { Group { if let scene = lookAroundScene { LookAroundPreview(initialScene: scene) } else { Button(action: { generateRandomCoordinate() }) { Text("Generate Random Coordinate") } .offset(y: yOffset) } } } } but it didn't work. I put the yOffset change there to debug, and it seems that self.lookAroundScene = scene never gets executed. If there are any other options, please let me know!
Posted Last updated
.
Post not yet marked as solved
0 Replies
326 Views
Hi. I want to make iOS app that when use camera AR, it can show someplace around me have annotations. ARGeoAnchor something but I don't have any idea. Can anyone give me some keywords? I can use Mapkit to search but don't know how to map it in AR.
Posted
by IrisHA233.
Last updated
.