Mapbox: Refreshing an annotationView when the annotation changes - ios

I have custom annotations that sometimes display a textView above them.
They don't display a textView if a variable named text on my annotation is nil.
An annotation may have text to display, but the value of the text variable could change while the annotation is being displayed. In this case I would like the annotation to refresh so that it is no longer displaying the textView.
I already have a delegate function that either creates an annotation with a textView if the annotations text variable is set and creates an annotation without a textView if the text variable of the annotation is not set, it works something like this, although this is not the actual code
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView?{
if annotation is MyCustomAnnotation{
if annotation.hasText(){
return MyCustomAnnotationView(hasText: True)
}else{
return ViewWithoutTextView(hasText: False)
}
}
But if the annotation changes from having text to not having text or vice versa while the annotation is already being displayed, then I don't know how to refresh this or call this again so that the right annotation view is displayed

As #Magnas said in the comment, you would have to remove the annotation and re-add it to update the state.
It would be better to create one custom annotation view that has the logic to handle hiding/showing of the text view inside it. Then you just hold onto a reference of the annotation and update that through the annotationView without going through and messing with map annotations at all.
A rough example (lots of blanks to fill):
// your methods in your custom annotation. Use these wherever you want to change things
class CustomAnnotation: MGLAnnotationView {
func showText() { }
func hideText() { }
}
// Define data structure to access your annotation with some kind of key
dataSourceToAnnotationView: [String: CustomAnnotation]
// save your annotations so you can access them later
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "customReuseId")
if annotationView == nil {
annotationView = CustomAnnotation()
let key = "exampleKeyString"
dataSourceToAnnotationView[key] = annotationView as! CustomAnnotation
}
return annotationView
}

Related

Guard let is executing, but the code after it still works?

Ok, so I have a MapKit app, and just finished setting up the MKAnnotationView stuff. My MKAnnotationView class looks like this:
class JumpSpotAnnotationView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? {
willSet {
// Extra safe, making sure there's no errors
guard (newValue as? JumpSpotAnnotation) != nil else {
print("The JumpSpotAnnotation or JumpSpotAnnotationView has something wrong if you are reading this. (JumpSpotAnnotationView)")
return
}
// Setting up UI for the little Callout bubble that appears when you tap the annotation to see more info
canShowCallout = true
calloutOffset = CGPoint(x: 0, y: 0)
rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
//detailCalloutAccessoryView
markerTintColor = .blue
}
}
}
And my mapView viewFor function in my view controller looks like this:
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Make sure the annotation entering the screen is a JumpSpotAnnotation, and exists
guard let annotation = annotation as? JumpSpotAnnotation else {
print("The JumpSpotAnnotation or JumpSpotAnnotationView has something wrong if you are reading this. (mapView viewFor func)")
return nil
}
// Downcast the dequeued view as a JumpSpotAnnotationView, and make sure it has the same identifier as the registered JumpSpotAnnotationView above in viewDidLoad
let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: "JumpSpotAnnotation") as? JumpSpotAnnotationView
dequeuedView?.annotation = annotation
// Return annotation views here
return dequeuedView
}
}
Honestly, I put the guard let's in each of those, because I saw someone else do it that way and assumed it would be safer. I'm not really sure what their purpose is, other than making sure an annotation is actually entering the view, and is of the right type of annotation that I specified (I think it does that, at least).
Anyway, when I actually add the annotations by pressing a button in my app, everything works flawlessly, exactly as I want it to, but the print statements inside of the guard let's are showing up in the debugger. I have no idea what's causing them, nor any idea why my code is still working after they've triggered, when the fact that the guard let's have executed should stop the code below them from executing, and mess up my app. Can anyone offer ideas or explanations? I should add that the print statement from the mapView viewFor func appears once, as soon as the app loads up, then, the print statement from my JumpSpotAnnotationView appears each time I add an annotation.
I want to make sure I'm not missing some huge error that I'll regret down the line.
There are some MKAnnotations that are not the class of JumpSpotAnnotation when func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? works. It must be from MKMapView so dont worry about it. Your guard let works well.

How can I change mapbox annotation view?

I've add several annotations with custom annotation view, but I have a reference only to the marker and not to the annotation view itself. So how can I change the annotation view elements?
You should store the annotations in a variable and when you want to change their views just remove them from the map with mapView.removeAnnotation(...) and add it back again with mapView.addAnnotation(...).
The method
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
}
will be called and you should return your changed view.
Pay attention to the fact that for performance reasons you should not use addAnnotation() or removeAnnotation() if you have a lot of annotations, but instead addAnnotations() and removeAnnotations()
I added all my annotation views to a dictionary
I created a global dictionary variable
var annotationViews = [CustomAnnotation:CustomAnnotationView]()
Then after creating each annotation view within my delegate function
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView?
I added it into my dictionary
let annotationView = MyAnnotationView(reuseIdentifier: rid, size: CGSize(width: 45, height: 45), annotation: annotation)
annotationViews[annotation as! MyAnnotation] = annotationView
Later when I wanted to change the text of a text view within my annotation view, I used my annotation in the dictionary call. This returned the annotation view that corresponded to it.
self.annotationViews[anno]?.textView.text = "My new text view status"
No deleting and re-adding required.
You could probably insert something smaller as the key for the dictionary, like annotation.uid or annotation.name or something. I just used the whole annotation object though

Creating a dynamic subview in swift iOS Map app

This is my first foray into the app world so it's taken a lot of research to get to this point. I'm building a map application and am going for an interface similar to the zillow app seen below. I am trying to come up with the right approach that allows me to click on a map annotation and it brings up a smaller view where I can interact with it. So essentially I have a few questions:
Should I use a subview inside the map controller, or use a container view. Or is there another approach I haven't seen?
How do I push data from the annotation to that function?
How do I keep this subview hidden until an annotation has been clicked?
So far this is the closest thing I can find: Customize MKAnnotation Callout View?
Thanks!
I am new to iOS also, but I have done something similar to what you want to do. I have a view that shows some statistics, speed, bearing, etc. When someone clicks on the annotation, I toggle showing and hiding the statistics. There may be better ways, but here is what I did.
"Executive summary for your questions"
1 and 3) Use a subview over the map that you hide and unhide
2) Subclass both MKAnnotation and MKAnnotationView. Put the data you want to pass in a property of the subclassed MKAnnotationView, and then transfer the property to the MKAnnotationView when you create it. You can then retrieve it from the view passed in to didSelectAnnotationView.
Details
1) and 3) I created a subview that sits on the mapView and set it as hidden in the story board initially. I then have a toggeleMarkerStatistics() func
tion that toggles the visibility of the view. So something like this
func toggleMarkerStatistics() {
if mapMarkerStatistics.hidden {
mapMarkerStatistics.hidden = false
} else {
mapMarkerStatistics.hidden = true
}
}
This function is called from within
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { }
2) To get data into the didSelectAnnotationView, here is what I did.
I subclassed both MKAnnotation and MKAnnotationView and added properties to hold the data that I wanted to pass to didSelectAnnotationView. So something like this:
class MyAnnotation: MKPointAnnotation {
var myMarker: MyMapMarker?
}
class MyMKAnnotationView: MKAnnotationView {
var myMarker: MyMapMarker?
}
When you create the annotation, set the property, before you add the annotation to the map.
let annotation = MyAnnotation()
annotation.myMarker = marker
annotation.coordinate = location
annotation.title = "btw, you MUST have a title or bad things happen"
mapView.addAnnotation(annotation)
Then in viewForAnnotation, you will be given your custom annotation with the property you set after you created it and you are asked to create a view for this annotation. Now when you create this view, set the view property to annotation property before you return the view. Now the data you want to pass to didSelectAnnotationView will be available on the view passed to didSelectAnnotationView
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let view: MKAnnotationView! = mapView.dequeueReusableAnnotationViewWithIdentifier("marker") ?? MyMKAnnotationView(annotation: annotation, reuseIdentifier: "marker")
view.annotation = annotation
view.canShowCallout = false // you need this to make this work
if let annotation = annotation as? MyAnnotation {
if let view = view as? MyMKAnnotationView {
view.myMarker = annotation.myMarker
}
}
return view
}
Now in didSelectAnnotationView, retrieve the data you set when you created the annotation:
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
if let view = view as? MyMKAnnotationView {
if let marker = view.myMarker {
toggleMarkerStatistics() // hide or unhide the view
// do something with your data
}
}
}
Note:
I tried to copy and simplify this from my code, which actually tries to support both Apple and Google maps, so hopefully I don't have any typo's, but I think is a good representation of the steps I take.
A few more things to note:
I think you must provide a title for the annotaion
I think you must set the view's canShowCallout to false
I think both of these requirements can be found in the documentation, but I don't have a pointer to this right now.

iOS Swift MapKit making an annotation draggable by the user?

How do I make it possible, using MapKit in Swift, for the user to drag an annotation from one position to another within the map? I have set the annotation view to be draggable, when my map view delegate creates the annotation view, like this:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var v : MKAnnotationView! = nil
if annotation is MyAnnotation {
let ident = "bike"
v = mapView.dequeueReusableAnnotationView(withIdentifier:ident)
if v == nil {
v = MyAnnotationView(annotation:annotation, reuseIdentifier:ident)
}
v.annotation = annotation
v.isDraggable = true
}
return v
}
The result is that the user can sort of drag the annotation - but only once. After that, the annotation becomes impossible to drag, and even worse, the annotation now no longer "belongs" to map - when the map is scrolled / panned, the annotation holds still rather than scrolling / panning with the map. What am I doing wrong?
It isn't enough to mark the annotation view by setting isDraggable to true. You must also implement mapView(_:annotationView:didChange:fromOldState:) in your map view delegate - and (even more important) this implementation must not be empty! Rather, your implementation must, at a minimum, communicate the drag state from the incoming parameters to the annotation view, like this:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
switch newState {
case .starting:
view.dragState = .dragging
case .ending, .canceling:
view.dragState = .none
default: break
}
}
Once you do that, the annotation will be properly draggable by the user.
(Many thanks to this answer for explaining this so clearly. I can't claim any credit! My answer here is merely a translation of that code into Swift.)

How to always show map view annotation callouts?

How do you always show the annotation callouts, i.e. don't hide them when you tab the map view?
Resetting the annotations also will bring the callout to view state true.
[mapView removeAnnotation: currentMarker];
[mapView addAnnotation:currentMarker];
The callout is shown when an MKAnnotationView is selected and the view's canShowCallout property is set to YES.
It is then hidden when that MKAnnotationView is deselected. This occurs by tapping another annotation view, or by tapping outside of the currently selected annotation view.
As the delegate of MKMapView (conforming to MKMapViewDelegate), you are told when an annotation view is selected and deselected, but it's too late to do anything about it.
If you want to not deselect an annotation view, you should subclass MKAnnotationView and override the setSelected:animated: method and stop the annotation view from being deselected.
Thanks, #Zumry Mohammed for this idea. This solution in swift works for me:
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
guard let ann = view.annotation else {return}
mapView.removeAnnotation(ann)
mapView.addAnnotation(ann)
mapView.selectAnnotation(ann, animated: false)
}
I just set isSelected property to true on viewFor annotation method and that is all.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationV = MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
annotationV.image = UIImage(named: "ZeusSurveyMarkerTaskIcon", in: Bundle(for: ZsurveysGeofenceLocationMapView.self), compatibleWith: nil)
annotationV.canShowCallout = true
annotationV.isSelected = true
return annotationV
}

Resources