Calculating expected travel time from set of polylines in iOS - 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
}
}

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

Show distance of route

First off, I would like to say I'm quite new to Swift. The simplest answer is probably the best in my situation.
I currently have some code that draws a route from my current location to the Grand Canyon, using the mapkit. The starting- and ending location is build in the code:
let soucrceCoordinates = locationManager.location?.coordinate
//coordinates off the grand canyon, placeholder
let destCoordinates = CLLocationCoordinate2DMake(36.1070, -112.1130)
let sourcePlacemark = MKPlacemark(coordinate: soucrceCoordinates!)
let destPlacemark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlacemark)
let destItem = MKMapItem(placemark: destPlacemark)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
Now I would like to calculate the distance of this route (not as the crow flies). The preferable unit would be meters. Is there anyway to do this? Thanks in advance
You have to create an MKDirections instance as well, not just an MKDirectionsRequest and call MKDirections.calculate to calculate the navigation routes.
let sourceCoordinates = locationManager.location?.coordinate
//coordinates of the grand canyon, placeholder
let destCoordinates = CLLocationCoordinate2D(latitude: 36.1070, longitude: -112.1130)
let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates!)
let destPlacemark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlacemark)
let destItem = MKMapItem(placemark: destPlacemark)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate(completionHandler: { response, error in
guard error == nil, let response = response, let route = response.routes.first else {return}
print("Distance:\(route.distance)meters")
})

Calculate distance and ETA from maps in swift

I am currently using this code below that will open maps with driving guide to a certain destination.
let lat1 : NSString = "57.619302"
let lng1 : NSString = "11.954928"
let latitute:CLLocationDegrees = lat1.doubleValue
let longitute:CLLocationDegrees = lng1.doubleValue
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitute, longitute)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span),
MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "Timo's Crib"
dispatch_async(dispatch_get_main_queue()) {
mapItem.openInMapsWithLaunchOptions(options)
}
}))
Now when the maps are opened you can see information such as ETA and total distance to destination. How can i extract or calculate that exact information? I only saw examples in objective c but never in swift.
You can do it using MKDirectionsRequest. First we need our current location, since from your code we see that you have the destination. I'm using CLLocationManagerDelegate method locationManager(_:didUpdateLocations:).
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let sourcePlacemark = MKPlacemark(coordinate: locations.last!.coordinate, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
..
}
Perfect. Now we have source item and destination item. Now just the request (to simplify things, I put your code inside the method, but the logic behind destination place should be probably extracted from this method):
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Get current position
let sourcePlacemark = MKPlacemark(coordinate: locations.last!.coordinate, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
// Get destination position
let lat1: NSString = "57.619302"
let lng1: NSString = "11.954928"
let destinationCoordinates = CLLocationCoordinate2DMake(lat1.doubleValue, lng1.doubleValue)
let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinates, addressDictionary: nil)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
// Create request
let request = MKDirectionsRequest()
request.source = sourceMapItem
request.destination = destinationMapItem
request.transportType = MKDirectionsTransportType.Automobile
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { response, error in
if let route = response?.routes.first {
print("Distance: \(route.distance), ETA: \(route.expectedTravelTime)")
} else {
print("Error!")
}
}
}

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/

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