Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS MapKit driving distance in time

When you search for a city etc in apple maps it also shows the time it takes to drive there next to the pointer. Is that something built in the mapKit API?

My code so far is:

import UIKit
import MapKit

class ShowMapViewController: UIViewController {

    var annotation:MKAnnotation!
    var localSearchRequest:MKLocalSearchRequest!
    var localSearch:MKLocalSearch!
    var localSearchResponse:MKLocalSearchResponse!
    var error:NSError!
    var pointAnnotation:MKPointAnnotation!
    var pinAnnotationView:MKPinAnnotationView!

    //Map
    @IBOutlet weak var mapView: MKMapView!

    //Exitbutton

    @IBAction func exitMapButtonDidTouch(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        //TODO: Search zip, if not found search city
        localSearchRequest = MKLocalSearchRequest()
        localSearchRequest.naturalLanguageQuery = "My city"
        localSearch = MKLocalSearch(request: localSearchRequest)
        localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in

            //Show city if zip not found
            if localSearchResponse == nil{
                var alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
                alert.show()
                return
            }

            //Show map and pointer
            self.pointAnnotation = MKPointAnnotation()
            //self.pointAnnotation.title = "My city" 
            self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse.boundingRegion.center.latitude, longitude:     localSearchResponse.boundingRegion.center.longitude)


            self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
            self.mapView.centerCoordinate = self.pointAnnotation.coordinate
            self.mapView.addAnnotation(self.pinAnnotationView.annotation)
        }

    }


}

With this I can add a title above the pointer but is it possible to show the time/distance as well?

Thanks in advance

like image 562
Kiwo Tew Avatar asked Oct 16 '25 19:10

Kiwo Tew


1 Answers

Yes that is something that is built in with Apple! It's called an MKRoute, and can give you travel time between two points.

You can create an MKRoute after preforming an MKDirectionsRequest.

Here's a link with a project that uses an MKDirectionsRequest, to apple documentation, and a link to EVEN MORE helpful documentation on the subject.

Best of luck!

like image 150
MQLN Avatar answered Oct 18 '25 13:10

MQLN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!