Swift handle did select on multiple annotations on same location - swift

I'm trying to call a function when annotations of the same location are selected. All I'm aiming for is to call a function and show a view controller with the two restaurants but for some reason, the function below isn't being called when I selected the marker in the image. (It works fine for single annotations). Thanks for any help.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let anno = view.annotation as? MyAnno else { return }
print(anno.post)
}

The problem lies in your guard statement. As I could find out in a short research, iOS uses a MKClusterAnnotation type for annotations that are equally located. Thus, the view variable does not have a .annotation set that confirms to your custom subclass.
In this case you need to try to cast it to a MKClusterAnnotation object, which in return has a property .memberAnnotations of type [MKAnnotation], which is what you want.
I think your code should look something like this (haven't tested it though):
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let anno = view.annotation as? MyAnno {
print("Single Annotation selected:")
print(anno.post)
// do anything
return
}
if let anno = view.annotation as? MKClusterAnnotations {
let selection: [MKAnnotation] = anno.memberAnnotations
print("\(selection.count) Annotations selected:")
// do something with your annotation group
// you should now also be able to cast to your MyAnno class again
for item in selection {
if let myAnno = item as? MyAnno {
print(myAnno.post)
}
}
}
}
For further information also take a look at Decluttering a Map with MapKit Annotation Clustering.

Related

Problem with callout button and firestore in swift

I have 5 collections on Firestore. With the data of the documents of those collections, I create annotations of different types and display them on a map view.
The problem is that I want to pass all the information that is stored in each annotation and display it on another view controller, that appears when you press the callout button.
I can't figure out a way of referencing the annotation I'm pressing and then pass the data to the other screen.
This is my first time using databases and I don't have many experience, so I would appreciate some help.
Thanks!
It's difficult to give a specific answer since I don't know the full scope of your features. But this is how you generally do it.
First when you create the MKAnnotation subclass, you define a property to hold an object that you can reference later. For example, say I'm showing restaurants and supermarkets in a map.
class RestaurantAnnotation: NSObject, MKAnnotation {
let restaurant: Restaurant
var title: String? {
return restaurant.name
}
var coordinate: CLLocationCoordinate2D {
return restaurant.coordinate
}
init(restaurant: Restaurant) {
self.restaurant = restaurant
super.init()
}
}
struct Restaurant {
let name: String
let coordinate: CLLocationCoordinate2D
}
Same goes for the supermarkets.
Then when you create the annotation, you pass the Restaurant object to it.
let restaurant = Restaurant(name: "McDonald's", coordinate: CLLocationCoordinate2D(latitude: 27.2831, longitude: -127.831))
let restaurantAnnotation = RestaurantAnnotation(restaurant: restaurant)
mapView.addAnnotation(restaurantAnnotation)
You implement the mapView(_:annotationView:calloutAccessoryControlTapped:) delegate method to be notified when the user taps on the callout button in annotations. In it, you can easily reference the object you passed to it earlier.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let annotation = view.annotation as? RestaurantAnnotation {
print(annotation.restaurant)
} else if let annotation = view.annotation as? SupermarketAnnotation {
print(annotation.supermarket)
}
}
And you can use that data to do whatever you want after that. In your case, pass it to a new screen.

I have a lot of annotation on my swift application. How can I only show the annotation on the map region currently visible?

I am trying to make an Uber clone in which there are a lot of annotation for passengers and driver. I want to only load and show the annotation which belong to the map region currently displayed, so that all the annotations are not added to the mapview and does not consume much memory.
I have two types of annotations: driver and passenger. I have different images for their annotation.
Here is how I am trying to do it:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? DriverAnnotation {
guard let dequeuedDriverAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: "driver") else {
let driverAnnotation = MKAnnotationView(annotation: annotation, reuseIdentifier: "driver")
driverAnnotation.image = UIImage(named: "driverAnnotation")
return driverAnnotation
}
dequeuedDriverAnnotation.annotation = annotation
return dequeuedDriverAnnotation
} else if let annotation = annotation as? PassengerAnnotation {
guard let dequeuedPassengerAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: "passenger") else {
let passengerAnnotation = MKAnnotationView(annotation: annotation, reuseIdentifier: "passenger")
passengerAnnotation.image = UIImage(named: "currentLocationAnnotation")
return passengerAnnotation
}
dequeuedPassengerAnnotation.annotation = annotation
return dequeuedPassengerAnnotation
}
return nil
}
}
How about defining function to check if annotation belong to the map region currently displayed, and try returning nil if it is out of region.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !visibleMapRegion(annotation) {
return nil
}
...
To define this function see also:
How to check if MKCoordinateRegion contains CLLocationCoordinate2D without using MKMapView?
How do I determine if the current user location is inside of my MKCoordinateRegion?

Find index of annotation MapKit

I have been trying to performSegue for annotation, but this code generates different indexes and wrong places are shown in detailsView. Would be great to find out how it is possible to fix this.
Thanks
var detailsDict = [NSDictionary]()
var selectedPlace: NSDictionary!
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if (view.annotation?.isKind(of: PlaceAnnotation.self))! {
let annotation = view.annotation
let index = (self.mapView.annotations as NSArray).index(of: annotation!)
let place = detailsDict[index]
selectedPlace = place
performSegue(withIdentifier: "showMuseumDetails", sender: self)
}
}
We can do it using this method
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
let annotation = view.annotation
let index = (self.mapView.annotations as NSArray).index(of: annotation!)
print ("Annotation Index = \(index)")
}
I think the main problem here is that you expect that mapView.annotations returns an array with all annotations being in the same order as your detailsDict-Array. I think that this assumption is error prone, because it would highly depend on the internal implementation of the MapKit framework.
A better way would be storing the Dictionary entry together with the PlaceAnnotation that you add to the map:
Add a new property details to class PlaceAnnotation
Set details value when you create the PlaceAnnotation
in calloutAccessoryControlTapped, get back the details property from the PlaceAnnotation
transfer this value to detail controller (maybe via your selectedPlace property, but I would prefer in instatiating the ViewController directly and setting the value).

mapView calloutAccessoryControlTapped, how to know who launched it?

I'm working on a project with a map, there are some annotations whose views have a detail button.
Those annotations are created in a for loop where I get data in JSON format, and for every element an annotation is created.
However there's no direct correlation between Annotations (or AnnotationViews) and those elements.
...
anView?.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
...
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
self.performSegueWithIdentifier("openInfo", sender: control)
}
I understand that this button calls the mapView function with calloutAccessoryControlTapped, and passes the AnnotationView.
The problem is that, even if I know the AnnotationView that called the segue, I don't know whose this responds to.
Is there any way to save some informations in the AnnotationView? I mean, so that every instance of AnnotationView has an ID that can relate to the data i received?
Any other idea?
Thanks
You can access the selected annotation from:
let selectedAnnotation = view.annotation as! CustomAnnotation // See structure below.
And if you have a data source which you want to access, it's recommended to create a custom object for your MKAnnotations that contain some reference to your data source, like an identifier. And then set:
selectedId = selectedAnnotation.id
performSegueWithIdentifier("openInfo", sender: control)
And in your prepareForSegue pass the selectedId to the receiving view controller.
EDIT: Your annotation class could look something like this:
class CustomAnnotation: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D
var subtitle: String?
var id: Int
init(title: String, coordinate: CLLocationCoordinate2D, subtitle: String, id: Int) {
self.title = title
self.coordinate = coordinate
self.subtitle = subtitle
self.id = id
}
}

How to change non selected annotation pin images on mapkit with Swift

I have a map and on this map, I have 10 custom annotation pins. All pins have the same custom image. When I click on a pin, I need to change all the other 9 annotation's images. it's possible to change the clicked pin's image but I need to keep as it is and I need to change all other pins images.
I tried to get all annotations with Map mapView.annotations and tried to find selected annotations and change other images but couldn't manage it. And idea how to do it?
Thanks in advance.
Conform to MKMapViewDelegate protocol and then:
func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
let selectedAnnotation = view.annotation
for annotation in mapView.annotations {
if let annotation = annotation as? MKAnnotation where !annotation.isEqual(selectedAnnotation) {
// do some actions on non-selected annotations in 'annotation' var
}
}
Also you can save the selected annotation for later use here, if you want to process all annotations in another moment.
finally managed :) solved the problem little bit hard way but working smooth :) thank you for the tip rshev ;)
i used a bool for tap recognize
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is CustomAnnotation {
var pin = mapView.dequeueReusableAnnotationViewWithIdentifier(customAnnotationViewIdentifier)
pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: customAnnotationViewIdentifier)
if tapControl {
pin.image = UIImage(named: "MapAnnotationIcon")
} else {
pin.image = UIImage(named: "SelectedMapAnnotationIcon")
}
if pin == nil {
pin.canShowCallout = false
} else {
pin.annotation = annotation
}
return pin
and when pin tapped ->
if let annotation = view.annotation as? CustomAnnotation {
tapControl = !tapControl
for annotation in mapView.annotations {
if let annotation = annotation as? MKAnnotation where !annotation.isEqual(selectedAnnotation) {
mapView.removeAnnotation(annotation)
}
}
addAnnotations()
println("tapped")
i removed all pins without selected pin, and then draw them back but this time tapcontrol is false so other pins are redrawed with another imageview, so thats what i exactly want to do.
You just have to overrride isSelected property inside your MKAnnotationView subclass.
override var isSelected: Bool {
didSet {
if isSelected {
// do stuff where annotation is selected
} else {
// do opposite
}
}
}