Skip to content

Instantly share code, notes, and snippets.

@stinger
Last active November 17, 2016 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stinger/cae843edc7efc60a248d188e6f8e2358 to your computer and use it in GitHub Desktop.
Save stinger/cae843edc7efc60a248d188e6f8e2358 to your computer and use it in GitHub Desktop.
Swift 3: MKMapView Helpers
import UIKit
import MapKit
extension MKMapView {
func showLocation(at coordinate: CLLocationCoordinate2D) {
self.removeOverlays(self.overlays)
self.removeAnnotations(self.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
self.addAnnotation(annotation)
self.centerCoordinate = annotation.coordinate
let region = MKCoordinateRegion(center: annotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.setRegion(region, animated: true)
}
func showDirections(from sourceLocation: CLLocationCoordinate2D, to destinationLocation: CLLocationCoordinate2D) {
self.removeOverlays(self.overlays)
self.removeAnnotations(self.annotations)
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = "Your Location"
if let location = sourcePlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.title = "Your Destination"
if let location = destinationPlacemark.location {
destinationAnnotation.coordinate = location.coordinate
}
self.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .walking
let directions = MKDirections(request: directionRequest)
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
var region = MKCoordinateRegionForMapRect(rect)
region.span = MKCoordinateSpanMake(0.005, 0.005)
self.setRegion(region, animated: true)
}
}
}
extension MainViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 4.0
return renderer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment