MapKit --- Map Framework in iOS
In iOS, you can simply use the MapKit framework to develop maps.
Basic Steps: import MapKit ViewController inherits the MKMapViewDelegate protocol and adds a MapKit View to prepare a corresponding region information, that is, where is the center, you can set the region in the mapView to add the location annotation. viewController
Import UIKitimport MapKitclass ViewController: UIViewController, MKMapViewDelegate {@ IBOutlet weak var mapView: MKMapView! Override func viewDidLoad () {super. viewDidLoad () // Do any additional setup after loading the view, typically from a nib. mapView. delegate = self // MKMapView has a delegate attribute. ViewController inherits the MKMapViewDelegate protocol and must implement the required method let location = CLLocationCoordinate2D (latitude: 22.284681, longpolling: 114.158177) let span = MKCoordinateSpanMake (0.05, 0.05) // region can be regarded as location-centric. let region = MKCoordinateRegion (center: location, span: span) // mapView: the map of the region is displayed. // mapView. mapType = MKMapType. standard mapView. setRegion (region, animated: true)} override func didReceiveMemoryWarning () {super. didReceiveMemoryWarning () // Dispose of any resources that can be recreated .}}
As shown in the preceding figure, you only need to prepare the location, and then you only need the setRegion operation of mapView to render the map.
Location annotation
In map, we can add an annotation at the specified position.
// Add a location annotation on the map. let annotation = MKPointAnnotation () annotation. coordinate = location annotation. title = "Hong Kong" annotation. subtitle = "Someplace" mapView. addAnnotation (annotation) // Add another location annotation on the map let location2 = CLLocationCoordinate2D (latitude: 22.294681, longpolling: 114.170177) let annotation2: MKPointAnnotation = MKPointAnnotation () annotation2.coordinate = location2 annotation2.title = "Hong Kong" annotation2.subtitle = "Someplace2" mapView. addAnnotation (annotation2)
Effect:
Annotation 1 |
Annotation 2 |
|
|
Operation during annotation display
Sometimes, we want to perform some operations when the map shows annotation, such as automatically placing or narrowing down the map.
// Call the func mapView (mapView: MKMapView !, DidAddAnnotationViews: [AnyObject]!) {Println ("didAddAnnotationViews") let annotationView: MKAnnotationView = views [0]! MKAnnotationView let annotation = annotationView. annotation let region: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance (annotation. coordinate, 500,500) self. mapView. centerCoordinate = region. center self. mapView. setRegion (region, animated: true) self. mapView. selectAnnotation (annotation, animated: true )}}
For example, once the annotation is displayed in the map, it automatically jumps to a region with the region center as the map center and specified range.
In addition, the next article is about to learn about the development of AMAP.