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
230 Views
Am just learning to use mapkit. Am attempting to draw 1 mile squares over a given region which can then me viewed on ipad or iphone. Ideally apple watch would provide haptic when such lines are crossed by the user. Where might I start?
Posted
by
Post not yet marked as solved
0 Replies
411 Views
Have a map. I have two pins. i have two buttons. When one button is pressed it goes to first pin. When second button is pressed it goes to second pin. The problem is if I move the map at all then press second button the first button vanishes and the map hasn’t moved - wonder if this is a bug. I can surely put the code
Posted
by
Post not yet marked as solved
1 Replies
1.1k Views
Hi, Can someone explain how the Map() position should work? struct ContentView: View { @State private var position: MapCameraPosition = .userLocation(followsHeading: true, fallback: .automatic) var body: some View { Map(position: $position) { UserAnnotation() } } } I was expecting the map to zoom in to users location but it shows the map zoomed out to the max instead. Location is authorized. I've also added the location button. .mapControls { MapUserLocationButton() } Pressing it zooms in to the user's location without issues. Thanks!
Posted
by
Post not yet marked as solved
3 Replies
1.2k Views
Map(position: $position, selection: $selectedResult) { MapPolyline(coordinates: track).stroke(.blue, lineWidth: 5) } When the @State track: [CLLocationCoordinates] is growing with new data (new coordinates appended) how can we reach that Map and MapPolyline is automatically refreshed?
Posted
by
Post marked as solved
3 Replies
1.8k Views
I've asked this question at SO, but there are no replies there, so I decided to give it a try here. Basically, I want to be able to capture the coordinates of a long press on the Map component (not the geo-coordinates - that's a separate task - just local to the app coordinates). The problem is that the .onLongPressGesture doesn't provide the coordinates of where the long press happened. .onTapGesture does - but I don't want to register taps, I want to register long presses. One of the work-arounds suggested at SO was to leverage the DragGesture, and it kinda works for other views, but when applied to a Map, it breaks the default dragging functionality of the Map component (so that it becomes impossible to scroll the map region). Also this work-around provides the coordinates only when the finger is released (at the end of the .onLongPressGesture), but I want to capture the long-press location before the finger was released (but after some time of holding, for example 1 second).
Posted
by
Post not yet marked as solved
0 Replies
710 Views
Hi, Tile overlays, the method to use other sources than Apple's maps, are not covered (yet). What would be the best way of implementing them now, in SwiftUI with the new MapKit? Thanks -Werner
Posted
by
Post not yet marked as solved
1 Replies
671 Views
what we must to use we need to take the user show on map to take the location and get some data or what we must to do with map is it become only to show our data and the user just move around and see data with MapCameraPosition that heavy work i wish there is another way ? i need to take the cunterly location on map
Posted
by
Post not yet marked as solved
4 Replies
1.6k Views
Hello, I'm following along with this tutorial, and am getting this error on the first steps of the video: Missing argument for parameter 'mapRect' in call Here is my code: import SwiftUI import MapKit struct ContentView: View { var body: some View { Map() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } Is the creator of the video somehow using a different version of the MapKit API than me? As far as I can tell, I am fully up-to-date. I'm on Ventura 13.4 using Xcode 14.3.1. I'm new to developing for Apple platforms, so maybe there's something obvious that I'm missing here?
Posted
by
Post not yet marked as solved
0 Replies
725 Views
I am flowing the code, but I have an error message coming when I code myself with Xcode for WWDC 23. The Section is Meet Mapkit for SwiftUI.
Posted
by
Post not yet marked as solved
0 Replies
564 Views
I'm currently playing with Apple Map's MapKit for SwiftUI, aiming to make a tool that helps me navigate inside the airport as I find out that Apple Map in my iPhone can direct me within the airport from gate to gate. I want to integrate this function into my SwiftUI application, but I believe that MapKit only gives directions between places to places, like from my home to the airport, but not directions travelling indoor in the airport. Are there any ways for me to integrate the Apple Map that supports airport's indoor navigation into my App? Thanks!
Posted
by
Post not yet marked as solved
0 Replies
347 Views
struct ImagePicker: UIViewControllerRepresentable { typealias UIViewControllerType = UIImagePickerController var sourceType: UIImagePickerController.SourceType var completionHandler: (UIImage?) -> Void func makeUIViewController(context: Context) -> UIImagePickerController { let imagePicker = UIImagePickerController() imagePicker.sourceType = sourceType imagePicker.delegate = context.coordinator return imagePicker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { // No update needed } func makeCoordinator() -> Coordinator { Coordinator(completionHandler: completionHandler) } final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { private let completionHandler: (UIImage?) -> Void init(completionHandler: @escaping (UIImage?) -> Void) { self.completionHandler = completionHandler } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { completionHandler(nil) picker.dismiss(animated: true) return } completionHandler(image) picker.dismiss(animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { completionHandler(nil) picker.dismiss(animated: true) } } } var body: some View { TabView { // Page 1: Map Search // Page 2: Photos VStack { Spacer() Menu { Button(action: { showImagePicker = true selectedImageSourceType = .photoLibrary }) { Label("Choose from Library", systemImage: "photo") } Button(action: { showImagePicker = true selectedImageSourceType = .camera }) { Label("Take Photo", systemImage: "camera") } } label: { Text("Memories") .font(.title) .foregroundColor(.black) } .padding() .sheet(isPresented: $showImagePicker, onDismiss: loadImage) { ImagePicker(sourceType: selectedImageSourceType ?? .photoLibrary) { image in selectedImage = image } } .padding() .sheet(isPresented: $showImagePicker, onDismiss: loadImage) { ImagePicker(sourceType: selectedImageSourceType ?? .photoLibrary) { image in selectedImage = image } } if !images.isEmpty { ScrollView { LazyVGrid(columns: [GridItem(.adaptive(minimum: 200, maximum: 700))], spacing: 20) { ForEach(images, id: \.self) { image in Image(uiImage: image) .resizable() .aspectRatio(contentMode: .fill) .frame(height: UIScreen.main.bounds.height / 5) .frame(width: UIScreen.main.bounds.width - 60) .cornerRadius(15) } } .padding() } } else { Text("No photos available") .foregroundColor(.gray) } } .tabItem { Image(systemName: "camera") Text("Memories") } .tag(1) } .accentColor(.blue) } @State private var encodedAddress = "" func fetchLocationInfoFromWikipedia(for address: String) { guard let encodedAddress = address.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro=true&explaintext=true&titles=\(encodedAddress)") else { self.encodedAddress = encodedAddress return } URLSession.shared.dataTask(with: url) { data, _, error in if let data = data { if let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let query = responseJSON["query"] as? [String: Any], let pages = query["pages"] as? [String: Any], let page = pages.keys.first, let pageData = pages[page] as? [String: Any], let extract = pageData["extract"] as? String { DispatchQueue.main.async { self.locationInfo = extract } } } } .resume() } func openWebsite(_ urlString: String) { if let encodedAddress = self.text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlString + encodedAddress) { UIApplication.shared.open(url) } } func loadImage() { guard let selectedImage = selectedImage else { return } images.append(selectedImage) self.selectedImage = nil } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Posted
by
Post not yet marked as solved
1 Replies
784 Views
Hello, Playing around with the MapJs Snapshot API. How many individual Overlays can it support? The docs say max for Images is 10 but not listing number of Overlays/Annotations it can support. Trying to generate a gradient path like so: But it seems the Apple Snapshot api only allows for 10 unique Overlay objects, is that true? Also, what's the max size of a Snapshot query url? Seems to stop working around 5,000 characters but Google allows for 8000+
Posted
by
Post not yet marked as solved
1 Replies
420 Views
Hello, I opened a ticket last week and got a nice email back with case # Case-ID: 3063780 I was hoping there was a link or something to click on to see if anybody was working on it, or was it just in the Que. There is a link to MFI (whatever that is) that I get an error saying I do not have access. I’ve been to my account and do not see any details. is there a JIRA page or something to show progress, or lack of, anywhere? If support had questions, I'm happy to answer. I want to be sure; no one is wait on me. Thanks Tom
Posted
by
Post not yet marked as solved
1 Replies
383 Views
import SwiftUI import MapKit import CoreLocation struct ContentView: View { @StateObject private var mapAPI = MapAPI() @State private var text = "" @State private var locationInfo: String = "" @State private var showLocationInfo = false @State private var imageUrls = [String]() // Array to store image URLs @State private var locationManager = CLLocationManager() @State private var isMovingOnMap = false func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { if manager.authorizationStatus == .authorizedWhenInUse { locationManager.startUpdatingLocation() } } @State private var showImagePicker = false @State private var showCamera = false @State private var selectedImage: UIImage? @State private var images: [UIImage] = [] @State private var selectedImageSourceType: UIImagePickerController.SourceType? struct ImagePicker: UIViewControllerRepresentable { typealias UIViewControllerType = UIImagePickerController var sourceType: UIImagePickerController.SourceType var completionHandler: (UIImage?) -> Void func makeUIViewController(context: Context) -> UIImagePickerController { let imagePicker = UIImagePickerController() imagePicker.sourceType = sourceType imagePicker.delegate = context.coordinator return imagePicker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { // No update needed } func makeCoordinator() -> Coordinator { Coordinator(completionHandler: completionHandler) } final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { private let completionHandler: (UIImage?) -> Void init(completionHandler: @escaping (UIImage?) -> Void) { self.completionHandler = completionHandler } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { completionHandler(nil) picker.dismiss(animated: true) return } completionHandler(image) picker.dismiss(animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { completionHandler(nil) picker.dismiss(animated: true) } } } var body: some View { TabView { // Page 1 ZStack(alignment: .topLeading) { Map(coordinateRegion: $mapAPI.region, interactionModes: .all, showsUserLocation: true) .edgesIgnoringSafeArea(.all) .gesture( DragGesture() .onChanged { gesture in isMovingOnMap = true showLocationInfo = false let translation = gesture.translation let currentRegion = mapAPI.region // Check if the horizontal drag distance is larger than the vertical distance if abs(translation.width) > abs(translation.height) { // Update the map's center coordinate based on the horizontal drag let mapWidth = UIScreen.main.bounds.size.width let coordinateSpan = currentRegion.span.longitudeDelta * Double(mapWidth) / 360.0 let coordinateDelta = CLLocationDegrees(translation.width) * coordinateSpan / Double(mapWidth) let updatedCenter = CLLocationCoordinate2D(latitude: currentRegion.center.latitude, longitude: currentRegion.center.longitude - coordinateDelta) let updatedRegion = MKCoordinateRegion(center: updatedCenter, span: currentRegion.span) DispatchQueue.main.async { mapAPI.region = updatedRegion } } else { // Update the map's region for vertical or diagonal drags (zooming) let span = currentRegion.span let spanMultiplier = min(span.latitudeDelta, span.longitudeDelta) / 500.0 let latitudeDelta = span.latitudeDelta - (translation.height * spanMultiplier) let longitudeDelta = span.longitudeDelta - (translation.width * spanMultiplier) let updatedRegion = MKCoordinateRegion(center: currentRegion.center, span: MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)) DispatchQueue.main.async { mapAPI.region = updatedRegion } } } .onEnded { _ in isMovingOnMap = false } ) VStack { HStack {
Posted
by
Post not yet marked as solved
2 Replies
2.1k Views
Hey guys, I recently started using Swiftui and would like to make a small app for my dad to use as a travel journal as my first project. He can create trips and then create multiple steps in a trip. When creating a step he should be able to set a location. Finding the location from the user is no problem. But now I also want to have the function to tap on the map and set a pin at a random location to get the coordinates (like google maps for example). Unfortunately I can't figure out from the documentation if there is a simple way to do this. import SwiftUI import MapKit struct StepLocationView: View { @EnvironmentObject var locationManagement: LocationDataManager @State private var position: MapCameraPosition = .automatic var body: some View { VStack { Map(position: $position) { UserAnnotation() } .navigationTitle("Search your location") .navigationBarTitleDisplayMode(.inline) .toolbarBackground(.visible, for: .navigationBar) .toolbarBackground(.ultraThinMaterial, for: .navigationBar) .edgesIgnoringSafeArea(.bottom) .onAppear{ position = .region(locationManagement.region) } .mapStyle(.standard(elevation: .realistic)) .mapControls { MapUserLocationButton() MapPitchButton() } } .background(Color.white) } } import SwiftUI import MapKit class LocationDataManager : NSObject, ObservableObject { @Published var location: CLLocation? @Published var region = MKCoordinateRegion() private let locationManager = CLLocationManager() override init() { super.init() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = kCLDistanceFilterNone locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() // info.plist has to be updated locationManager.delegate = self } } extension LocationDataManager: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } self.location = location self.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude), latitudinalMeters: 5000, longitudinalMeters: 5000) }; } I really appreciate your help, Marius
Posted
by