Search code examples
iosswiftmapboxmapbox-marker

MapBox in Swift - Allowing a marker's annotation to have a button that links to a View


I have set up a simple app with a tabbed map view (map on tab 1) that reads info from a json file on a server (point info is stored in MySQL) with SwiftyJSON and Alamofire. The points are loaded into the map. What I would like to do is add a button to the annotation, which outlets to a different view tab and passes along the point's ID.

I have not tried anything yet as I have no idea where to get started and the documentation doesn't mention anything similar.

How does one go about adding an outlet to a map point annotation?


Solution

  • When you tap your pin the callout appears with a title and/or a subtitle. You need to add left and right callout accessory views to this callout. You do this by conforming to the MGLMapViewDelegate and implementing the following methods:

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
            return true
    }
    
    func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
        ...your code here...
        let deleteButton = UIButton(type: .custom)
        deleteButton.tag = 100
    }
    
    func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
        ...your code here...
        let infoButton = UIButton(type: .custom)
        infoButton.tag = 101
    }
    
    func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
        ...your code here...
        switch control.tag {
        case 100:
           // do some delete stuff
        case 101:
           // do some info stuff
        default:
           break 
    }
    

    The MapBox example showing actual usage is here: MapBox example. This example doesn't segue but you would just trigger a segue with the button tap instead of the UIAlert.