简体   繁体   中英

Swift 2: How can I save a place/location the user searches on a map?

The user can search any location, but how can i save that location in the app in a different View Controller. In other words, there's a pin with the title of the location in the location, I want the user to click in that pin with the title and proceed to the next view Controller were the location will appear with the title. How can I do that with Swift 2?

Here's the code so far to get the pin. There's also a code to search an address not included here. What I want is to be able to tap on the title of that pin and go to another View Controller were you can see part of the map and that pin and be able to do more things in this view controller.

protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}

class ViewController: UIViewController {
  let locationManager = CLLocationManager()
var resultSearchController:UISearchController? = nil
var selectedPin:MKPlacemark? = nil


@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()

    //
    let locationSearchTable =        storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTable") as! LocationSearchTable
    resultSearchController = UISearchController(searchResultsController: locationSearchTable)
    resultSearchController?.searchResultsUpdater = locationSearchTable
    //
    let searchBar = resultSearchController!.searchBar
    searchBar.sizeToFit()
    searchBar.placeholder = "Search for places"
    navigationItem.titleView = resultSearchController?.searchBar
    //
    resultSearchController?.hidesNavigationBarDuringPresentation = false
    resultSearchController?.dimsBackgroundDuringPresentation = true
    definesPresentationContext = true
    //
    locationSearchTable.mapView = mapView
    //
    locationSearchTable.handleMapSearchDelegate = self
    //
    let button   = UIButton(type: UIButtonType.System) as UIButton
    button.frame = CGRectMake(100, 100, 100, 50)
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

extension ViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if status == .AuthorizedWhenInUse {
        locationManager.requestLocation()
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: location.coordinate, span: span)
        mapView.setRegion(region, animated: true)
    }
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("error:: \(error)")
}
}

extension ViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
    // cache the pin
    selectedPin = placemark
    // clear existing pins
    mapView.removeAnnotations(mapView.annotations)
    let annotation = MKPointAnnotation()
    annotation.coordinate = placemark.coordinate
    annotation.title = placemark.name
    if let city = placemark.locality,
        let state = placemark.administrativeArea {
        annotation.subtitle = "\(city) \(state)"
    }
    mapView.addAnnotation(annotation)
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegionMake(placemark.coordinate, span)
    mapView.setRegion(region, animated: true)

}
}

Welcome to SO. This is a CS 101 type question. Or maybe iOS 101.

A location starts out as a CLLocation object. It gets saved to a map as an object that conforms to the MKAnnotation protocol.

The key bit is a location, a CLLocationCoordinate2D , which is just a struct.

At the time you add a pin to your map, you should have the lat/long, since you need to call the map view's addAnnotation method to add an annotation pin, passing in an object that conforms to the MKAnnotation protocol (which means it has a coordinate property.)

What part of getting this to work don't you understand? How to respond to a tap on the map pin? How to add a button to the resulting callout view? How to use tapping on the button on the callout view to instantiate a new view controller from the storyboard and present it? How to pass the coordinates of the pin to the other view controller?

I would advise against triggering another view controller when the user simply taps on a pin. the user's expectation is that that will show a callout view. If you are sure that's what you want to do, though, you'd implement the map view delegate method mapView:didSelectAnnotationView:

Better to create a custom callout view with an accessory view, put a button in the accessory view, and trigger your view controller when the user taps the button in the accessory view.

Please don't ask me to give you code showing how to do this. I've given you enough for you to start reading and figure it out. (The code I have is in Objective-C anyway, so you'd probably have a hard time making sense of it.)

I suggest you look for tutorials on MapKit ( MKMapView ) callout accessory views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM