Tuesday 11 November 2014

Swift + CLGeocoder to show address string on Map

First of all add & Import MapKit framework in your class.

import UIKit
import MapKit

class ViewController: UIViewControllerCLLocationManagerDelegate
{

    @IBOutlet weak var map: MKMapView!
    
  
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
       self.map.mapType = MKMapType.Standard
       self.map.showsUserLocation = true
        
       self.map.removeAnnotations(self.map.annotations)

     

         let address = "address string"
        
        var geocoder:CLGeocoder = CLGeocoder()
        
        geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in
            
            if(error != nil)
            {
                
                println("Error", error)
            }
                
            else if let placemark = placemarks?[0] as? CLPlacemark
            {
                
                var placemark:CLPlacemark = placemarks[0] as CLPlacemark
                var coordinates:CLLocationCoordinate2D = placemark.location.coordinate
                
                var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = coordinates
                pointAnnotation.title = "Apple HQ"
                
                self.map.addAnnotation(pointAnnotation)
                self.map.centerCoordinate = coordinates
                self.map.selectAnnotation(pointAnnotation, animated: true)
                
                println("Added annotation to map view")
            }
            
        })

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }

}

No comments:

Post a Comment