Transfer Mkmapview to Another Controller Without Loading Map Again

Implement location tracking using MapKit in Swift

Location-based services have e'er looked like a very cool feature to me. Showing the user their covered or targeted location and route made the process of moving around so much better. In this web log, we will attempt to implement MapKit, a very simple and easy framework provided by Apple, to work upon with map and location requirements. Our aim will be to implement location tracking services and prove the covered road on Map View. This will be done using Swift.

mapkit_practice

Create Xcode project

To start off, open Xcode, and select the option Create a new Xcode project. From there, select iOS->Application->Single View Awarding, and click on Next. Later entering your project proper noun cull language as Swift.

To work with location services and MapKit, you will have to add MapKit and CoreLocation frameworks from Project Settings->Build Phases->Link binary with Libraries.

Now go to file ViewController.swift and add these two lines to import MapKit and CoreLocation framework through the view controller.

import MapKit import CoreLocation

Initial Setup

At present become to storyboard file and add together map view to your view controller, present in Object library. Create a property of your mapview on view controller file and name information technology mapView.

Assign your view Controller to CLLocationManagerDelegate and MKMapViewDelegate .

For authorizing app to location services, add NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription keys to your project's Info.plist. Add the following cord against your authority keys, "Your Project wants to utilise your present location".

Time to start Coding…!! 🙂

First create a holding of CLLocationManager by adding the following line:

var locationManager: CLLocationManager!        

After that lets do some setup for locationManager to become it working. Add the following lines of code in func viewDidLoad()

locationManager = CLLocationManager() locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.delegate = self;        

To consummate the authorization process for enabling location services, add the post-obit lines of code

// user activated automated authorization info mode var status = CLLocationManager.authorizationStatus() if status == .NotDetermined || condition == .Denied || status == .AuthorizedWhenInUse {        // present an warning indicating location potency required        // and offer to take the user to Settings for the app via        // UIApplication -openUrl: and UIApplicationOpenSettingsURLString        locationManager.requestAlwaysAuthorization()        locationManager.requestWhenInUseAuthorization()    } locationManager.startUpdatingLocation() locationManager.startUpdatingHeading()

Now, run your project. As soon as your awarding launches, you will encounter an authorization alert on the awarding screen. Assuasive that will enable the application to go location of user.

Simply where to get that location from???

In order to become the user's electric current location, implement the CLLocationManager delegate:

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)

Then, add the following lines to impress the obtained user location

println("nowadays location : (newLocation.coordinate.latitude), (newLocation.coordinate.longitude)")

Now run your projection and you will see logs for changing location of user.

NOTE : If you lot are non getting any location, click on the Simulator and select Debug->Location->City Bike Ride. This will produce a simulated route for a location. The route calculation is done by Apple tree.

Map Setup

So, how well-nigh displaying live user location on the Map?

To get the visible user location from the map, add the post-obit lines in func viewDidLoad()

//mapview setup to show user location mapView.delegate = self mapView.showsUserLocation = true mapView.mapType = MKMapType(rawValue: 0)! mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!        

Now run your project and you will run across the user location change in the map.

Showing Route On Map

At present nosotros will show the route covered by a user.
To do that, add the following lines in CLLocationManager delegate

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)

//cartoon path or route covered if let oldLocationNew = oldLocation as CLLocation?{      let oldCoordinates = oldLocationNew.coordinate      let newCoordinates = newLocation.coordinate      var area = [oldCoordinates, newCoordinates]      var polyline = MKPolyline(coordinates: &area, count: area.count)      mapView.addOverlay(polyline)  }        

Only that isn't enough. The above code volition just add together overlay equally road on map. But to render overlay on the map, another MKMapView delegate func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! is required.

Add the post-obit lines inside the delegate mentioned above

if (overlay is MKPolyline) {     var pr = MKPolylineRenderer(overlay: overlay)     pr.strokeColor = UIColor.redColor()     pr.lineWidth = five     return pr } render aught        

Run the project and y'all volition be able to run into a trail of red colour, behind the user location i.e. the route.

Finish off by adding annotations to the route

To add annotations, add together the following function that takes CLLocation as statement and draws annotation at required location. It is done after getting the location name from the coordinates through CLGeocoder and applying information technology to title of notation.

//office to add annotation to map view func addAnnotationsOnMap(locationToPoint : CLLocation){      var notation = MKPointAnnotation()     annotation.coordinate = locationToPoint.coordinate     var geoCoder = CLGeocoder ()     geoCoder.reverseGeocodeLocation(locationToPoint, completionHandler: { (placemarks, mistake) -> Void in         if permit placemarks = placemarks as? [CLPlacemark] where placemarks.count > 0 {             var placemark = placemarks[0]             var addressDictionary = placemark.addressDictionary;             notation.title = addressDictionary["Name"] equally? String             cocky.mapView.addAnnotation(notation)         }     }) }        

Now when you're calling this function directly from CLLocationManager consul, information technology will add annotations on the map. But past doing so information technology makes the map clusterized.

To solve this problem nosotros will add the annotations every time we embrace a distance of 200 metres.

For that remove the telephone call to the function func addAnnotationsOnMap(locationToPoint : CLLocation) and add together the following lines in CLLocationManager consul.

//adding for location selection and pointing annotation if permit previousLocationNew = previousLocation as CLLocation?{     //case if previous location exists     if previousLocation.distanceFromLocation(newLocation) > 200 {         addAnnotationsOnMap(newLocation)         previousLocation = newLocation     } }else{     //in instance previous location doesn't be     addAnnotationsOnMap(newLocation)     previousLocation = newLocation }

As before long equally you add these lines you will get an error for unknown variable previousLocation. To solve the event add the following holding

var previousLocation : CLLocation!

Now run your project and you can see the route likewise as annotations (not clusterized), along with user location, existence tracked on map.

Thats all folks!

To find a sample projection of the in a higher place tutorial, bank check GitHub.

I promise the weblog was simple and help y'all learn MapKit improve. Feel free to comment in example of queries and any other advice.

pannellangleatild.blogspot.com

Source: https://www.innofied.com/implement-location-tracking-using-mapkit-in-swift/

0 Response to "Transfer Mkmapview to Another Controller Without Loading Map Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel