Get road distance with MapKit - Swift - ios

What are the classes I should look into if I want to get road distance?
All I want to be able to get is the road-distance from point A to point B, I don't need to show step by step directions nor the map.
Any suggestions?
Thanks

You need to make a MKDirections request. From calculateDirectionsWithCompletionHandler you will get a MKDirectionsResponse. This has a routes array of MKRoutes. Each route has a distance (i.e. road distance) property.
let source = MKMapItem( placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(-41.27, 173.28),
addressDictionary: nil))
let destination = MKMapItem(placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(-41.11, 173),
addressDictionary: nil))
let directionsRequest = MKDirectionsRequest()
directionsRequest.source = source
directionsRequest.destination = destination
let directions = MKDirections(request: directionsRequest)
directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
print(error)
let distance = response!.routes.first?.distance // meters
print("\(distance! / 1000)km")
}

Related

MapKit: How to update the polyline on the map upon the movement of one of the annotations

I am working on an app like Uber. I succeeded in drawing the line between the user and the driver on the map but I want also to track the driver movements, how to update the polyline according to driver moves.
Note: I have an API that I can get the current location of the driver.
let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlaceMark)
let destinationItem = MKMapItem(placemark: destinationPlaceMark)
let sourceAnotation = MKPointAnnotation()
sourceAnotation.title = sourceAddress
if let location = sourcePlaceMark.location {
sourceAnotation.coordinate = location.coordinate
}
let destinationAnotation = MKPointAnnotation()
destinationAnotation.title = destinationAddress
if let location = destinationPlaceMark.location {
destinationAnotation.coordinate = location.coordinate
}
mapView.showAnnotations([sourceAnotation, destinationAnotation], animated: true)
let directionRequest = MKDirections.Request()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationItem
directionRequest.transportType = .automobile
let direction = MKDirections(request: directionRequest)
direction.calculate { (response, error) in
guard let response = response else {
if let error = error {
print("ERROR FOUND : \(error.localizedDescription)")
}
return
}
let route = response.routes[0]
mapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)
You already have the most important part working, getting driver's location, and drawing a route to it.
Now, you can simply run a timer and periodically perform following steps:
get driver location
check if new location is different (beyond some threshold) from previous location
calculate new route with updated location
remove old route polyline overlay
add new route polyline overlay

How to launch Maps app and start navigation

In my iOS app I have latitude and longitude (CLLocationCoordinate2D) of a place the user would like to reach. I want than, when the relative button is pressed, that Maps application is launched and that street navigation to that place is started too. How can I achieve that? My code up to now is:
#IBAction func launchMapsApp(sender:UIButton) {
if (sender == self.navButton) {
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: self.currentCoordinates, addressDictionary: nil))
mapItem.name = ""
//You could also choose: MKLaunchOptionsDirectionsModeWalking
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: true]
mapItem.openInMapsWithLaunchOptions(launchOptions as? [String : AnyObject])
}
}
But with this the Maps app is simply launched and I simply see a map of my state (Italy) and nothing more happens. Maybe, because I have run in only in simulator?
Thanks to all
You were on the right track: This is my swift 2.0 code:
let latitude:CLLocationDegrees = xx.xxxxx
let longitude: CLLocationDegrees = xx.xxxxx
let regiondistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionspan = MKCoordinateRegionMakeWithDistance(coordinates, regiondistance, regiondistance)
let options = MKLaunchOptionsMapCenterKey:NSValue(MKCoordinate:regionspan.center),MKLaunchOptionsMapSpanKey:NSValue(MKCoordinateSpan:regionspan.span)]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapitem = MKMapItem(placemark: placemark)
mapitem.name = "Name you want"
mapitem.openInMapsWithLaunchOptions(options)
I hope my code gives you some insight.
Your original code looks about right. It's possible, as you said, that the issue was how you were using the simulator. You can set a simulated location via the Debug menu in the simulator (Location -> Custom).
To launch Maps and start navigation to a specific location (as opposed to just opening Maps with a marker at the desired location, as in the other answer), I use this (in Swift 3):
let coordinates = CLLocationCoordinate2DMake(destLatitude, destLongitude)
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapitem = MKMapItem(placemark: placemark)
let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
mapitem.openInMaps(launchOptions: options)
Hope this helps...

How to draw route (without polylines) and without google api?

I want to draw route on Map without using google API.
I am tracking the user with co-ordinates of user. So i draw polylines to show user route,but now my client wants to remove those polylines and want to show routes like google have. Is it possible in which i can pass all co-ordinates route map drawn on those co-ordinates?
Actually you can use MKDirections built-in MapKit Framework. here's the further information: https://developer.apple.com/library/mac/documentation/MapKit/Reference/MKDirections_class/.
Show you some snippet which is calculating the route of two locations:
func caculateDirections(fromCoordinate: CLLocationCoordinate2D, toCoordinate: CLLocationCoordinate2D) {
let from = MKMapItem(placemark: MKPlacemark(coordinate: fromCoordinate, addressDictionary: nil))
let to = MKMapItem(placemark: MKPlacemark(coordinate: toCoordinate, addressDictionary: nil))
let request = MKDirectionsRequest()
request.source = from
request.destination = to
request.transportType = .Automobile
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
if let response = response {
// Here you can get the routes and draw it on the map
let routes = response.routes
} else {
print("Error:\(error?.description)")
}
}
}
You can learn more from this tutorial: http://www.devfright.com/mkdirections-tutorial/

Calculating expected travel time from set of polylines in iOS

I have a set of polylines defining a route. Is there some way that I can use mapkit to calculate the expected travel time along this route? If not in MapKit, then in Google Maps or any other maps api?
let sourcePlaceMark = MKPlacemark(coordinate: fromCoordinate, addressDictionary: nil)
let destPlaceMark = MKPlacemark(coordinate: toCoordinate, addressDictionary: nil)
let from = MKMapItem(placemark: sourcePlaceMark)
let to = MKMapItem(placemark: destPlaceMark)
print("caculateDirections ")
let request = MKDirectionsRequest()
request.source = from
request.destination = to
request.transportType = .Automobile
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
if let response = response {
// Here you can get the routes and draw it on the map
let routeSeconds = response.routes.first!.expectedTravelTime
let routeDistance = response.routes.first!.distance
}
}

iOS - MapKit and navigation from a location to another

my question is about the mapkit in the iOS SDK. Is it possible to draw routes from a location to another? Is there any built-in API? If no, how can I do?
Thanks
In iOS 7, there is an API for getting the direction from a location to another called MKDirection. You can call -[MKDirection calculateDirectionsWithCompletionHandler:] method for that. This method's argument is MKDirectionsHandler block which contains the MKDirectionsResponse. The MKDirectionsResponse contains the routes data which is array of MKRoute. In each MKRoute there is a polyline (MKPolyline) which you can add these polyline as overlays to the MKMapView.
MKDirections allows you to find routes between two locations and MapKit allows you to add this routes as an overlay.
func drawRoutes(sourceLocation:CLLocationCoordinate2D ,
destinationLocation:CLLocationCoordinate2D)
{
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 directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .automobile
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.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}

Resources