Ticker

6/recent/ticker-posts

MKMapView tutorial in Swift

What is MapView?

An MKMapView object provides an embeddable map interface. Where we can load set of locations information on the top of view.

How to use MKMapView  in realtime application?

Let's start creating new application. Open Xcode, go to File\New\New Project, select iOS\Application\Single View Application then click next and name the project and select language as Swift.
After creating new project we need to add MapKit.framework  to our project, to do that select Project\Target\Build Phases\Link Binary With Libraries  then click (+) sign which lists all the frameworks, search for MapKit and click add button.

Before going to coding part, we need to setup location authorization in the Info.plist by adding NSLocationWhenInUseUsageDescription and some information about why we are using locations.


Now import MapKit.framework in ViewController.swif then start coding to create MKMapView object.


import UIKit
import MapKit

class ViewController: UIViewController {

    var _mapView:MKMapView!
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        

        //create mapview object and add it to the main view
        _mapView = MKMapView(frame: self.view.bounds)
        _mapView.delegate = self
        _mapView.showsCompass = true
        _mapView.showsTraffic = true
        _mapView.showsBuildings = true
        self.view.addSubview(_mapView)
         
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

The MKMapView requires MKAnnotation to be displayed as locations. To add annotations to the mapview, create new class as Annotation  which confirms the MKAnnotation protocols as shown below.

File\New\Cocoa Touch Class then click next


Name your class as Annotation then click next

After creating Annotation class import Mapkit framework and try to conform MKAnnotation  protocol properties in that class, as shown below.

import UIKit
import MapKit


class Annotation: NSObject,MKAnnotation {
    let title: String?
    let subtitle: String?
    let coordinate: CLLocationCoordinate2D

    
    
    //to customize my collout
    var imageName : String?
    
    
    init(title aTitle:String, subtitle aSubTitle:String, aCoordinate:CLLocationCoordinate2D){
        self.coordinate = aCoordinate
        self.title  = aTitle
        self.subtitle = aSubTitle
        super.init()
    }
    
}

Now come back to ViewController.swift, let's create Annotation object which are of individual locations with location name, location information and location coordinates and add them to mapview.

//create annotation objects which will be displayed on mapview
let location1 : Annotation = Annotation(title: "Bangalore", subtitle: "31°C, Wind W at 23 km/h, 52% Humidity", aCoordinate: CLLocationCoordinate2DMake(12.9716, 77.5946))
location1.imageName = "bangalore"
        
let location2 : Annotation = Annotation(title: "Kolkata", subtitle: "26°C, Wind SE at 10 km/h, 100% Humidity", aCoordinate: CLLocationCoordinate2DMake(22.5726, 88.3639))
location2.imageName = "kolkata"

let location3 : Annotation = Annotation(title: "Mumbai", subtitle: "32°C, Wind SW at 14 km/h, 66% Humidity", aCoordinate: CLLocationCoordinate2DMake(19.0760, 72.8777))
location3.imageName = "mumbai"

let location4 : Annotation = Annotation(title: "Hyderabad", subtitle: "30°C, Wind N at 27 km/h, 66% Humidity", aCoordinate: CLLocationCoordinate2DMake(17.3850, 78.4867))
location4.imageName = "hyd"


//add all annotation to the mapview
_mapView.addAnnotations([location1,location2,location3,location4])
Now specify the particular location that should be shown initially with some zoom.

        
//specifys the zoom level of perticular location area
_mapView.setRegion(MKCoordinateRegionMake(location4.coordinate, MKCoordinateSpanMake(12, 12)), animated: true) 
Note: If you want to increase zoom level then reduce the values of MKCoordinateSpan.

Authorizing user locations:

In order to authorize user locations we need to write the following code snippet .
        
func checkLocationAuthorizationStatus() {
        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            _mapView.showsUserLocation = true
        } else {
            locationManager.requestWhenInUseAuthorization()
        }
}
 The use of this method is to display an alert for requesting locations permissions. Now you can clearly see that why configured NSLocationWhenInUseUsageDescription key in the Info.plist



If you want to change default pin to some custom pin, you just need to conform the following protocol of MKMapViewDelegate as show below.

extension ViewController:MKMapViewDelegate{
    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        
        var button : AAButton
        var iconView : UIImageView
        if let annotation = annotation as? Annotation {
            let identifier = "pin"
            var view: MKPinAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
                as? MKPinAnnotationView {
                //reused view
                view = dequeuedView
            } else { //very first time
                view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                view.canShowCallout = true
                //add annotation to the view
                view.annotation = annotation
                
                //right view
                button = AAButton(type: .DetailDisclosure)
                view.rightCalloutAccessoryView = button;
                
                
                //left view
                iconView = UIImageView(frame: CGRectMake(0, 0, 40, 40))
                iconView.contentMode = .ScaleAspectFill;
                view.leftCalloutAccessoryView = iconView;
            }
            
            //custom pin image
            view.image = UIImage(named: "pin")
            
            //right view action
            button = view.rightCalloutAccessoryView as! AAButton
            button.annotation = annotation
            button.addTarget(self, action: #selector(ViewController.showDetailLocation(_:)), forControlEvents: .TouchUpInside)
            
            
            //left view content
            iconView = view.leftCalloutAccessoryView as! UIImageView
            iconView.image = UIImage(named: annotation.imageName!)

            
            return view
        }
        return nil
    }
    
    func showDetailLocation(button:AAButton) {
        print("tapped location \(button.annotation?.title!)")
    }
}

Before going to hit run, let's enable the user locations by clicking Edit Schema...


After done with everything, now run the application. You can download complete code from here.

Post a Comment

0 Comments