Newbie Questions
Newbie Questions

Reputation: 463

how to set action to search's cancel button

i have a search function with my mapView so you can search for annotation. and i would like to add an option that when i press the cancel button the trackingMode of user location will be true ,so the map will center on the user location again . How can it be done? here is my search code :

   override func viewDidLoad() {
        super.viewDidLoad()

        //==========RegionLocation : =========

        // Init the zoom level
        let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.30, longitude: 34.45)
        let span = MKCoordinateSpanMake(125, 125)
        let region = MKCoordinateRegionMake(coordinate, span)
        self.mapView.setRegion(region, animated: true)


        //====================================\\



        //==============Tel Aviv==============
        self.mapView.delegate = self
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true


         // Drop a pin
        let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)
 let searchTable = storyboard!.instantiateViewController(withIdentifier: "SearchTableViewController") as! SearchTableViewController

        searchController = UISearchController(searchResultsController: searchTable)
        searchController?.searchResultsUpdater = searchTable
        searchController?.hidesNavigationBarDuringPresentation = false
        searchController?.dimsBackgroundDuringPresentation = true

            definesPresentationContext = true

            let searchBar = searchController!.searchBar
            searchBar.sizeToFit()
            searchBar.placeholder = "חפש ברים"
            navigationItem.titleView = searchController?.searchBar
            searchBar.delegate = self

            searchTable.mapView = mapView
            searchTable.handleMapSearchDelegate = self
    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])


    {
        let location = locations.last

        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.06, longitudeDelta: 0.06))

        self.mapView.setRegion(region, animated: true)

        self.locationManager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Errors: " + error.localizedDescription)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
        let reuseID = "pin"

        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) as? MKPinAnnotationView
        if(pinView == nil) {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = false
            pinView!.image = UIImage (named: "")
            pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIButton
            let smallSquare = CGSize(width: 40, height: 40)
            let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
            button.setBackgroundImage(UIImage(named: "Car2"), for: UIControlState())
            pinView?.leftCalloutAccessoryView = button

        }
        else
        {
            pinView?.annotation = annotation
        }

        return pinView

    }


    func openMapsAppWithDirections(to coordinate: CLLocationCoordinate2D, destinationName name: String) {
        let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
        let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = name // Provide the name of the destination in the To: field
        mapItem.openInMaps(launchOptions: options)


        func openMapsAppWithDirections(_ latitude: Double, longitude: Double) {
            if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                //Waze is installed. Launch Waze and start navigation
                let urlStr = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                UIApplication.shared.openURL(URL(string: urlStr)!)
            }
            else {
                //Waze is not installed. Launch AppStore to install Waze app
                UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
            }
        }



    }

    func mapView(_ MapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped controll: UIControl) {
        if controll == annotationView.rightCalloutAccessoryView {
            let segueID: String = "BarsProfile" // Use the appropriate segue ID here
            performSegue(withIdentifier: segueID, sender: self)}

            if controll == annotationView.leftCalloutAccessoryView {
                if let annotation = annotationView.annotation {
                    // Unwrap the double-optional annotation.title property or
                    // name the destination "Unknown" if the annotation has no title
                    let destinationName = (annotation.title ?? nil) ?? "Unknown"
                    openMapsAppWithDirections(to: annotation.coordinate, destinationName: destinationName)


                        }
                    }
            }
    func updateMap(_ location: CLLocation)  {
        let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 150, 150)
        mapView.setRegion(region, animated: true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        print("Cancel!")
        updateMap(CLLocation(latitude: currentLoc.coordinate.latitude, longitude: currentLoc.coordinate.longitude))
    }

}



extension MapViewController: HandleMapSearch   {
    func dropPinZoomIn(placemark: MKAnnotation)    {
        updateMap(CLLocation(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude))
        searchController.searchBar.text = placemark.title!
    }

thanks for helping hope someone can solve me my problem

Upvotes: 0

Views: 300

Answers (1)

Mike G
Mike G

Reputation: 104

Assuming you're referring to the searchBar's cancel button, you need to implement the searchBarCancelButtonClicked delegate method in the master viewController. Based on the code I had posted to GitHub, add this method to ViewController.swift.

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    updateMap(CLLocation(latitude: currentLoc.coordinate.latitude, longitude: currentLoc.coordinate.longitude))
}

Also, declare currentLocation outside of viewDidLoad

var currentLoc:MKPointAnnotation!

Upvotes: 2

Related Questions