Created
April 6, 2015 07:29
-
-
Save jacks205/e06563f066015b94df28 to your computer and use it in GitHub Desktop.
MKMapKit showing route and zooming to show source and destination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// MapDirections | |
// | |
// Created by Mark Jackson on 4/5/15. | |
// Copyright (c) 2015 Mark Jackson. All rights reserved. | |
// | |
import UIKit | |
import MapKit | |
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { | |
@IBOutlet weak var mapView: MKMapView! | |
var locationManager : CLLocationManager? | |
var currentlocation : CLLocation? | |
var searched : Bool = false | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
self.initializeLocationManager() | |
mapView.showsUserLocation = true | |
mapView.delegate = self | |
println("First") | |
} | |
override func viewDidAppear(animated: Bool) { | |
super.viewDidAppear(animated) | |
} | |
//Initialize Location Manager and update location | |
func initializeLocationManager(){ | |
self.locationManager = CLLocationManager() | |
if let locationManagerOp = self.locationManager{ | |
locationManagerOp.delegate = self; | |
locationManagerOp.distanceFilter = kCLDistanceFilterNone | |
locationManagerOp.desiredAccuracy = kCLLocationAccuracyBest | |
locationManagerOp.requestWhenInUseAuthorization() | |
locationManagerOp.startMonitoringSignificantLocationChanges() | |
locationManagerOp.startUpdatingLocation() | |
} | |
} | |
func findPlace(){ | |
let req : MKLocalSearchRequest = MKLocalSearchRequest() | |
if let currentPosition = self.currentlocation{ | |
req.region = MKCoordinateRegionMakeWithDistance(currentPosition.coordinate, 50000, 50000) | |
} | |
req.naturalLanguageQuery = "Irvine Spectrum" | |
let localSearch : MKLocalSearch = MKLocalSearch(request: req) | |
localSearch.startWithCompletionHandler { (res : MKLocalSearchResponse!, error : NSError!) -> Void in | |
if error != nil{ | |
println(error.localizedDescription) | |
// self.tableView.reloadData() | |
}else{ | |
if let mapItems = res.mapItems as? [MKMapItem]{ | |
for item in mapItems{ | |
self.placeRoute(item) | |
break | |
} | |
} | |
} | |
} | |
} | |
func placeRoute(dest : MKMapItem){ | |
let request = MKDirectionsRequest() | |
request.setSource(MKMapItem(placemark: MKPlacemark(coordinate: self.currentlocation!.coordinate, addressDictionary: nil))) | |
request.setDestination(dest) | |
request.requestsAlternateRoutes = false | |
let directions = MKDirections(request: request) | |
directions.calculateDirectionsWithCompletionHandler({(response: | |
MKDirectionsResponse!, error: NSError!) in | |
if error != nil { | |
// Handle error | |
println(error) | |
} else { | |
self.showRoute(response) | |
} | |
}) | |
} | |
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { | |
self.currentlocation = locations.first as? CLLocation | |
if !self.searched{ | |
findPlace() | |
self.searched = true | |
} | |
} | |
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { | |
switch (status){ | |
case .AuthorizedAlways: | |
println("Authorized!") | |
break | |
default: | |
break | |
} | |
} | |
func showRoute(response: MKDirectionsResponse) { | |
for route in response.routes as [MKRoute] { | |
mapView.addOverlay(route.polyline, | |
level: MKOverlayLevel.AboveRoads) | |
for step in route.steps { | |
println(step.instructions) | |
} | |
} | |
var southWest : CLLocationCoordinate2D = response.destination.placemark.coordinate; | |
var northEast : CLLocationCoordinate2D = southWest; | |
southWest.latitude = min(southWest.latitude, response.source.placemark.coordinate.latitude); | |
southWest.longitude = min(southWest.longitude, response.source.placemark.coordinate.longitude); | |
northEast.latitude = max(northEast.latitude, response.source.placemark.coordinate.latitude); | |
northEast.longitude = max(northEast.longitude, response.source.placemark.coordinate.longitude); | |
let locSouthWest : CLLocation = CLLocation(latitude:southWest.latitude, longitude:southWest.longitude); | |
let locNorthEast : CLLocation = CLLocation(latitude:northEast.latitude, longitude:northEast.longitude); | |
// This is a diag distance (if you wanted tighter you could do NE-NW or NE-SE) | |
let meters : CLLocationDistance = locSouthWest.distanceFromLocation(locNorthEast) | |
let mapPadding = 1.1 | |
let minVisibleLatitude = 0.0 | |
var region : MKCoordinateRegion = MKCoordinateRegion( | |
center: CLLocationCoordinate2D( | |
latitude: (southWest.latitude + northEast.latitude) / 2.0, | |
longitude: (southWest.longitude + northEast.longitude) / 2.0), | |
span: MKCoordinateSpan( | |
latitudeDelta: (northEast.latitude - southWest.latitude) * 2, | |
longitudeDelta: (northEast.longitude - southWest.longitude) * 2)) | |
region.span.latitudeDelta = (region.span.latitudeDelta < minVisibleLatitude) | |
? minVisibleLatitude | |
: region.span.latitudeDelta; | |
let fittedRegion = self.mapView.regionThatFits(region) | |
self.mapView.setRegion(fittedRegion, animated: false) | |
} | |
func mapView(mapView: MKMapView!, rendererForOverlay | |
overlay: MKOverlay!) -> MKOverlayRenderer! { | |
let renderer = MKPolylineRenderer(overlay: overlay) | |
renderer.strokeColor = UIColor.blueColor() | |
renderer.lineWidth = 5.0 | |
return renderer | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment