Post not yet marked as solved
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?
Post not yet marked as solved
The new Mapkit for SwiftUI improvements are much welcomed. Are custom map callouts available? Thank you.
Post not yet marked as solved
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
Where is the source code for Meet MapKit for SwiftUI video ?
Post not yet marked as solved
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!
I really would like to avoid installing any beta versions, when can i expect the SDK to be available and deployed for us to use?
Post not yet marked as solved
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?
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).
Post not yet marked as solved
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
Post not yet marked as solved
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
Post not yet marked as solved
is it possible, to allow the user updating the marker position like with the MKMarkerAnnotationView.isDraggable attribute available in a MkMapView?
Subject says it all: is or will there be a way to download offline maps programmatically?
Post not yet marked as solved
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?
Post not yet marked as solved
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.
Post not yet marked as solved
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!
Post not yet marked as solved
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()
}
}
Post not yet marked as solved
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+
Post not yet marked as solved
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
Post not yet marked as solved
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 {
Post not yet marked as solved
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