Post not yet marked as solved
What I am trying to accomplish:
Navigate to MapView defined in ProfileMapView. - This works
In ProfileMapView, when calloutAccessoryControlTapped method is called Navigate from ProfileMapView when to another view: ProfileDetailsView- This is does not work
//Calling ProfileMapview like this:
@State var pins = [GpsData.MyEndPt]()
ProfileMapView(locationPins: $pins)
// ProfileMapView defined
struct ProfileMapView: View {
@Environment(\.managedObjectContext) private var viewContext
@Environment(\.dismiss) var dismiss
@State var tracking:MapUserTrackingMode = .follow
@Environment(\.presentationMode) var presentationMode
@Binding var locationPins: [GpsData.MyEndPt]
var body: some View {
TabView {
NavigationView {
ZStack {
VStack (alignment: .leading){
MapView(locationPins: $locationPins)
.ignoresSafeArea()
}
}
//.edgesIgnoringSafeArea(.all)
.safeAreaInset(edge: .bottom) {
Color.clear
.frame(height: 0)
.background(.white)
}
}
}
struct MapView: UIViewRepresentable {
@Binding var locationPins: [GpsData.MyEndPt]
func makeUIView(context: Context) -> MKMapView {
//...
}
func updateUIView(_ uiView: MKMapView, context: Context) {
//...
}
func makeCoordinator() -> MapViewDelegate{
var del = MapViewDelegate()
del.addEndPoints(endPoints: locationPins)
return del
}
class MapViewDelegate: MKMapView, MKMapViewDelegate {
let PINID:String = "MyEndPoint"
var mylocationPins: [GpsData.MyEndPt] = []
@State var locationId: String?
@State var providerType: String?
public func addEndPoints(endPoints: [GpsData.MyEndPt]) {
self.mylocationPins = endPoints
self.removeAnnotations(endPoints)
self.addAnnotations(endPoints)
self.showAnnotations(endPoints, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var mPin: MKMarkerAnnotationView? = nil
let subtitleView = UILabel()
for pin in self.mylocationPins {
if (mPin == nil ) {
mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID)
mPin?.canShowCallout = true
} else{
mPin?.annotation = annotation
}
mPin?.rightCalloutAccessoryView = UIButton(type: UIButton.ButtonType.detailDisclosure)
subtitleView.text = "Target: "
subtitleView.text! += String(pin.target)
}
mPin!.detailCalloutAccessoryView = subtitleView
return mPin!
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
DispatchQueue.main.async {
if let thumbnailImageButton = view.leftCalloutAccessoryView as? UIButton,
let url = (view.annotation as? GpsData.MyEndPt)?.thumbnailUrl
{
print("URL: \(url)")
do{
let imageData: Data = try Data(contentsOf: url as URL)
let image = UIImage(data: imageData)
thumbnailImageButton.setImage(image, for: UIControl.State.normal)
}catch{
print("Unable to load image data: \(error)")
}
}
}
}
//MARK:- delegate method
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
mapView.deselectAnnotation(view.annotation, animated: true)
for detail in self.mylocationPins {
locationId = detail.locationId
providerType = detail.providerType
NavigationLink(value: control) {
ProfileDetailsView(locationId: $locationId, providerType: $providerType)
}
break
}
}
}
}
}
}
ProfileDetailsView defined like this:
@StateObject var manager = LocationManager()
@State var tracking:MapUserTrackingMode = .follow
@Environment(\.presentationMode) var presentationMode
@Binding var locationId: String?
@Binding var providerType: String?
var body:some View {
VStack (alignment: .leading){
Text("Details here...")
Button {
}
label: {
Text("Share")
.foregroundColor(.blue)
}
.buttonStyle(.bordered)
Button {
}
label: {
Text("Update consumption")
.foregroundColor(.blue)
}
.buttonStyle(.bordered)
}
}
}
I get warning: "Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update." inside ProfileMapView line wheer I define @Binding var locationPins: [GpsData.MyEndPt]. That value is being passed into ProfileMapView - so I dont know why then warning.
However, ProfileMapView gets called, the mapview is displayed and the marker pin appears and when I click on the disclosure the navigation to other view ProfileDetailsView does not work. I tried NavigationStack and could not make it work because it threw lot of errors. How to fix the code in calloutAccessoryControlTapped method, so I can navigate to other view: ProfileDetailsView. I have spent a week on this trying various things but it hasn't worked.
Post not yet marked as solved
Two separate app projects need maps or navigation:
Offline map: offline vector map of small city needed within the app (avoiding any online connection after the app's install). Apple Maps requires map tile download after installation. What is an alternative solution?
Navigation: An app with a list of locations where we don't want to build-in maps or navigation. Would it be possible to allow the user to click on a location, app copies GPS coordinates, and opens default iOS navigation app and navigates from there instead?
Working in Xcode with Swift and SwiftUI.
Post not yet marked as solved
I'm trying to adapt my current production ready iOS/iPadOS 17 app to visionOS and I'm trying it directly running the app for the Apple Vision Pro (Designed for iPad) target.
I have a bottom sheet to show Map items detail by tapping on the Map Annotations. The bottom sheet is opening properly with a normal Button action but it's not opening by Annotation which wrapped Button action. It pops up as expected on iOS/iPadOS but on VisionOS it doesn't.
Annotation("", coordinate: result.coordinate) {
Button(action: { ... } )
})
Post not yet marked as solved
From core data I generate data for map marker pins. When user selects a marker pin I display the data in a popup label with multiple rows, when I click on the pin. This is working for one marker pin. Now, I need to iterate over a list and generate several of those markers each with unique popup label data.
The code:
struct MapView: UIViewRepresentable {
var annotationOnTap: (_ title: String) -> Void
@Binding var pins: [GpsData.MyEndPt]
let key: String
private static var mapViewStore = [String : MKMapView]()
func makeUIView(context: Context) -> MKMapView {
if let mapView = MapView.mapViewStore[key] {
mapView.delegate = context.coordinator
return mapView
}
let mapView = MKMapView(frame: .zero)
mapView.delegate = context.coordinator
MapView.mapViewStore[key] = mapView
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
uiView.addAnnotations(pins)
}
func makeCoordinator() -> MapCoordinator {
MapCoordinator(self)
}
final class MapCoordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let PINID:String = "MyEndPoint"
var mPin: MKMarkerAnnotationView? = nil
let subtitleView = UILabel()
subtitleView.font = subtitleView.font.withSize(12)
subtitleView.numberOfLines = 0
if (mPin == nil ) {
mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID)
mPin?.canShowCallout = true
} else{
mPin?.annotation = annotation
}
mPin?.leftCalloutAccessoryView = nil
let btn = UIButton(type: .detailDisclosure)
mPin?.rightCalloutAccessoryView = btn
let zip:String = "77065"
let formattedSalesStr:String = "100"
let totalTargetText:String = "500"
let paddedLoad = formattedSalesStr.padding(toLength: 50, withPad: " ", startingAt: 0)
let paddedCapacity = totalTargetText.padding(toLength: 50, withPad: " ", startingAt: 0)
subtitleView.text = "Total sales: "
subtitleView.text! += paddedLoad
subtitleView.text! += " \r\n"
subtitleView.text! += "Total Target: "
subtitleView.text! += paddedCapacity
subtitleView.text! += " \r\n"
subtitleView.text! += paddedzip
mPin!.detailCalloutAccessoryView = subtitleView
return mPin!
}
}
}
As you can see in the above method I have hardcoded values for my popup marker label. So I tried to iterate over the @Binding pins, populate each mPin, and return an array of MKAnnotationView, like this:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> [MKAnnotationView] {
let PINID:String = "MyEndPoint"
var i:Int = 1
var mPins = [MKAnnotationView]()
for detail in self.parent.pins {
var mPin: MKMarkerAnnotationView? = nil
let subtitleView = UILabel()
subtitleView.font = subtitleView.font.withSize(12)
subtitleView.numberOfLines = 0
if (mPin == nil ) {
mPin = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: PINID)
mPin?.canShowCallout = true
} else{
mPin?.annotation = annotation
}
mPin?.leftCalloutAccessoryView = nil
let btn = UIButton(type: .detailDisclosure)
mPin?.rightCalloutAccessoryView = btn
subtitleView.text! += String(i)
subtitleView.text = "Total Load: "
subtitleView.text! += String(detail.sales)
subtitleView.text! += " \r\n"
subtitleView.text! += "Total Target: "
subtitleView.text! += String(detail.target)
subtitleView.text! += " \r\n"
i += 1
// }
mPin!.detailCalloutAccessoryView = subtitleView
mPins.append(mPin!)
}
return mPins
}
The marker pins show up, but then the label does not popup. How to fix this?
Post not yet marked as solved
I have a LookAroundPrewiew in a frame which itself is already small. On top of that is the LookAroundPreview automatically appended onto the preview. In fact it doesn’t really bother me per se, but it’s that my view doesn’t have much space. So is it possible customize the view by removing the text ? And the Apple Maps text at the bottom of the image which is fairly small isn’t a problem for me.
Post not yet marked as solved
Hello dear developers, I am planning to make a navigation application for the swift student challenge, this navigation application will work with the internet via apple maps, is it suitable for this swift student challenge competition?
Post not yet marked as solved
Hi everyone! I'm working on an app to submit to the Swift Student Challenge this year and wanted to get some feedback on my plan to use MapKit.
I know Apple is pretty open to using any of their frameworks for the contest. But I wanted to see if anyone had insights on whether my use of MapKit would comply with the contest rules and eligibility criteria.
Any thoughts or advice you have on properly leveraging MapKit for my submission would be much appreciated! I want to make sure I avoid any issues since this framework is so integral to my app idea. Let me know if you have built a map-based app for Swift Student Challenge before as well. Thanks!
Post not yet marked as solved
Hello,
I'm working on a SwiftUI/MapKit project. It uses a custom annotation to mark zip codes on the map. I have an onTapGesture configured to run a custom function when the user clicks on the RoundedRectangle content included in the Annotation.
I'm using the .annotationTitles(.hidden) modifier on the Annotation so that the title is not shown below my custom annotation. However, when I click below my annotation (where the hidden title text would be) the normal MapKit selection behavior executes. My project has Markers on the map in which I do want this behavior. It pulls up a half sheet detail view for the Marker. It does not make sense for this half sheet detail view to be displayed when tapping on a zip code.
I tried using a ZStack with a transparent rectangle offset to drop below my annotation (yellow in screenshot), and included the same onTapGesture with custom function for this. My hope was that the transparent (yellow) RoundedRectangle would override the behavior of clicking on the hidden title. This didn't work.
Any ideas? Thanks for your help!
Post not yet marked as solved
how to add an offline map (longitude and latitude) please help
Post not yet marked as solved
I understand that MapKit automatically sizes the font based on the system Dynamic Type size.
The thing is, the default font size is plenty legible for me system wide except for some type in MapKit, while other type in MapKit is already plenty big.
For instance, the stream names are much harder to read than they should be by default. And if I increase the system Dynamic Type size, then it makes some MapKit text much larger than needed, while the stream text can still be hard to read.
So is there anyway to override or adjust font sizes in MapKit? I'd like to be able to apply percentages to Dynamic Type suggestions. Like for streams, I'd like to scale it somewhere between 133% and 150%.
The smallest Dynamic Type is size is .caption2 at 11 points with default settings. With default Dynamic Type settings, it looks like MapKit is drawing stream text around 7 points.
Post not yet marked as solved
I am making an app like Taxi Driving, where users can add location and driver to that location. The problems I am facing are below:
Drawing a route on MKMap - I get the route polyline and I render that on the map. Now what should happen as I am driving, the drove part of the polyline should get removed or may be turned grey, non-drove part should be blue. Currently, I am only able to do this by again getting a route from my current location and re-drawing on the map which is not a good thing I suppose.
Show driving instructions - I need to show step-by-step instructions which I get in the MKStep under the MKRoute object. But I don't get the icons that I can show such as Turn Right or Turn left the only thing I have is plain text. I need an icon along with it and also how to identify once I have crossed the step and show the next step as my next instruction.
These two are the major problems I am facing and I need to do this with Apple native map view itself so no third-party integration I want.
Post not yet marked as solved
I'm developing a map-based app for visionOS. The loads map data from a server, using JSON. It works just fine, but I noticed the following effect: If I move the app's window around, it freezes; either on the first movement, or on one of the subsequent ones. The map cannot be panned anymore, and all other UI elements lose their interactivity as well.
I noticed this issue before, when I was opening the map on app startup (and here it even happened without moving the window). Since I added a short delay, this was resolved. There was no log message in this case.
However, when I noticed that it also happens if I move the window around, I saw that Xcode logs an error:
+[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behavior. trace=(
0 UIKitCore 0x0000000185824a24 __42+[UIView(Animation) setAnimationsEnabled:]_block_invoke + 112
1 libdispatch.dylib 0x0000000102a327e4 _dispatch_client_callout + 16
2 libdispatch.dylib 0x0000000102a34284 _dispatch_once_callout + 84
3 UIKitCore 0x0000000185824ad8 +[UIView(Animation) performWithoutAnimation:] + 56
4 SwiftUI 0x00000001c68cf1e0 OUTLINED_FUNCTION_136 + 10376
5 SwiftUI 0x00000001c782bebc OUTLINED_FUNCTION_12 + 22864
6 SwiftUI 0x00000001c78285e8 OUTLINED_FUNCTION_12 + 8316
7 SwiftUI 0x00000001c787c288 OUTLINED_FUNCTION_20 + 39264
8 SwiftUI 0x00000001c787c2cc OUTLINED_FUNCTION_20 + 39332
9 UIKitCore 0x000000018582fc24 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1496
10 QuartzCore 0x000000018a05cf00 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 440
11 QuartzCore 0x000000018a068ad0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 124
12 QuartzCore 0x0000000189f80498 _ZN2CA7Context18commit_transactionEPNS_11TransactionEdPd + 460
13 QuartzCore 0x0000000189fb00b0 _ZN2CA11Transaction6commitEv + 652
14 VectorKit 0x00000001938ee620 _ZN2md12HoverSupport18updateHoverProxiesERKNSt3__16vectorINS1_10shared_ptrINS_5LabelEEEN3geo12StdAllocatorIS5_N3mdm9AllocatorEEEEE + 2468
15 VectorKit 0x0000000193afd1cc _ZN2md15StandardLabeler16layoutForDisplayERKNS_13LayoutContextE + 156
16 VectorKit 0x0000000193cf133c _ZN2md16CompositeLabeler16layoutForDisplayERKNS_13LayoutContextE + 52
17 VectorKit 0x0000000193abf318 _ZN2md12LabelManager6layoutERKNS_13LayoutContextEPKNS_20CartographicRendererERKNSt3__113unordered_setINS7_10shared_ptrINS_12LabelMapTileEEENS7_4hashISB_EENS7_8equal_toISB_EEN3geo12StdAllocatorISB_N3mdm9AllocatorEEEEERNS_8PassListE + 2904
18 VectorKit 0x0000000193cad464 _ZN2md9realistic16LabelRenderLayer6layoutERKNS_13LayoutContextE + 464
19 VectorKit 0x0000000193658b54 _ZNSt3__110__function6__funcIZN2md9realistic20RealisticRenderLayer5frameERNS2_13LayoutContextEE3$_0NS_9allocatorIS7_EEFvvEEclEv + 180
20 VectorKit 0x00000001936584cc ___ZN3geo9TaskQueue14queueAsyncTaskENSt3__110shared_ptrINS_4TaskEEEPU28objcproto17OS_dispatch_group8NSObject_block_invoke + 80
21 libdispatch.dylib 0x0000000102a30f98 _dispatch_call_block_and_release + 24
22 libdispatch.dylib 0x0000000102a327e4 _dispatch_client_callout + 16
23 libdispatch.dylib 0x0000000102a3aa80 _dispatch_lane_serial_drain + 916
24 libdispatch.dylib 0x0000000102a3b7c4 _dispatch_lane_invoke + 420
25 libdispatch.dylib 0x0000000102a3c794 _dispatch_workloop_invoke + 864
26 libdispatch.dylib 0x0000000102a481a0 _dispatch_root_queue_drain_deferred_wlh + 324
27 libdispatch.dylib 0x0000000102a475fc _dispatch_workloop_worker_thread + 488
28 libsystem_pthread.dylib 0x0000000103b0f924 _pthread_wqthread + 284
29 libsystem_pthread.dylib 0x0000000103b0e6e4 start_wqthread + 8
I disabled all my withAnimation() statements, and the problem persists. I also thought it might be related to my own network fetches, but I think all apply their changes on the main thread. And when I turn on network logging for my own fetching logic, I do not see any data coming in. I also do not think there should be a reason for it.
How can I debug such a situation, so I know, which call actually threw this message? I'd like to know if it is my code or a bug in the SwiftUI map itself.
Post not yet marked as solved
Hi, I am learning about MapKit for SwiftUI, at first I created the MKMapItem
@State private var mapSelection: MKMapItem?
@State var starbucksReserve = MKMapItem(placemark: .init(coordinate: CLLocationCoordinate2D(latitude: 41.894178596474575, longitude: -87.62451598445733)))`
I put that in the Map
Map(position: $cameraPosition,selection: $mapSelection){
Marker("Starbucks Reserve", systemImage: "cup.and.saucer.fill" ,coordinate: starbucksReserve.placemark.coordinate)
}
Even though I have put the selection $mapSelection, my Marker is not selectable. I am not sure why. I tried to fix it by changing mapSelection to Int? and made a tag for Marker, but because I am learning how to use it so I want to make sure why marker cannot be selectable with the first approach?
Thank you
Post not yet marked as solved
According to the MKMapview, all annotations should be added to the map:
https://developer.apple.com/documentation/mapkit/mkmapview
When configuring your map interface, be sure to add all of your annotation objects right away. The map view uses the coordinate data in each annotation object to determine when the corresponding annotation view needs to appear onscreen. When an annotation moves onscreen, the map view asks its delegate to create a corresponding annotation view. If your app has different types of annotations, it can define different annotation view classes to represent each type.
But this has a very low performance when the map is zoomed out and all annotations are visible (although market already filters out most of the annotations and only displays a few). As fas as I've seen, the suggestion from the documentation doesn't scale properly when the number of annotations is very large.
Grouping doesn't help, neither using reusable annotations.
Is the only option here, handling manually the add/remove annotations as the map rect changes?
Post not yet marked as solved
In UIKit, we can add an insets to a MKMapView with setVisibleMapRect to have additional space around a specified MKMapRect. It's useful for UIs like Apple Maps or FlightyApp (see first screenshot attached). This means we can have a modal sheet above the map but still can see all the content added to the map.
I'm trying to do the same for a SwiftUI Map (on iOS 17) but I can't find a way to do it: see screenshot 2 below. Is it possible to obtain the same result or should I file a feedback for an improvement?
Post not yet marked as solved
**Hi, hopefully you can help me with this swiftUI code?
I have created a Map App which will show a route via a ManPolyLine (see the code).
Whilst I can print the route via the (in the code below)
var _ = print("ROUTE = (route.steps.map { $0.instructions }.filter { !$0.isEmpty })")
I CANNOT create a variable for the route it prints?
I need to do this so I can create a .sheet (which is shown), but cannot
Access a Variable to List the route details!
Help would be most appreciated,
TIA
(The pertinent part of the code below)**
===========================================
@State private var route: MKRoute?
@State private var myRoute: [String] = []
@State private var selectedResult: MKMapItem?
@State private var position: MapCameraPosition = .automatic
Map(position: $position, selection: $selectedResult)
{
ForEach(searchResults, id: \.self) {
result in
Marker(item: result)
}
.annotationTitles(.hidden)
UserAnnotation()
if let route {
MapPolyline(route)
.stroke(.blue, lineWidth: 5)
var myRoute = route.steps.map { $0.instructions }.filter { !$0.isEmpty }
var _ = print("ROUTE = \(route.steps.map { $0.instructions }.filter { !$0.isEmpty })")
var _ = print("COUNT = \(myRoute.count)")
}
}
===========================================
Post not yet marked as solved
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?
Post not yet marked as solved
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?
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?
Post not yet marked as solved
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.