W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/19/2021

Simple MapView tutorial in Swift - MapKit

 The MapKit framework providing the map details on the iOS device. By use of the MapKit, we can display location, annotation on Map, adding Overlay, Draw route on Map , add shapes on Map, and also find the Placemark information from MapKit framework. 



This tutorial only provide simple map integration and display  pin on Map with MKPointAnnotation.

Step 1 : Open Xcode 7.3 and create new project name as "MapDemo". also fill other details like organization name, organization identifier, etc.

Step 2 : Open Storyboard and drag & drop MapView in ViewController. Give the MapKit View the same size as its main view. so set autolayout constrain of MapKit view. see the below image.

Step 3 : Connect MapKit View with IBOutlet in ViewController.Swift.

Step 4 : Go to the ViewController.Swift class and import MapKit framework in this file.
1import MapKit
Step 5 : Now add the code in ViewDidLoad of ViewController Class. 
1)  You are set the type of the MapType using MKMapType. 
2) Define location CLLocationCoordinate2D with the latitude and longitude. 
3) MKCoordinateSpanMake which use to Span according to Location NorthToSouth and EastToWest.
4) Add the MKPointAnnotation on MapView with its Title and SubTitle.

12345678910111213141516171819202122override func viewDidLoad() {
    super.viewDidLoad()

    // 1)
    mapV.mapType = MKMapType.Standard

    // 2)
    let location = CLLocationCoordinate2D(latitude: 23.0225,longitude: 72.5714)

    // 3)
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: location, span: span)
    mapV.setRegion(region, animated: true)

    // 4)
    let annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "iOSDevCenter-Kirit Modi"
    annotation.subtitle = "Ahmedabad"
    mapV.addAnnotation(annotation)

}

MapView with Pin Annotation according to its coordinate.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.