Wednesday, October 1, 2014

CLGeocoder().geocodeAddressString - Show the input address on the map

1. Add the mapkit and a UITextField in the storyboard and edit the code as below:

import MapKit
import CoreLocation
import AddressBookUI

@IBOutlet weak var theMap: MKMapView!

class ViewController: UIViewController, CLLocationManagerDelegate {

Also include the MapKit and CoreLocation frameworks in the project.

2. Control-drag the text field to the Swift file and set:

Connection: Action
Name: addressInput
Type: UITextField
Event: Did End On Exit
Arguments: Sender

and click "connect."

3. Edit the code as below:

    @IBAction func addressInput(sender: UITextField) {
        var placemark: CLPlacemark!
        CLGeocoder().geocodeAddressString(sender.text, completionHandler: {(placemarks, error)->Void in
            if error == nil {
                placemark = placemarks[0] as CLPlacemark
                self.theMap.setRegion(MKCoordinateRegionMake(CLLocationCoordinate2DMake (placemark.location.coordinate.latitude, placemark.location.coordinate.longitude), MKCoordinateSpanMake(0.002, 0.002)), animated: true)


No comments:

Post a Comment