How to launch Maps app and start navigation - ios

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...

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

What is wrong with this code? When it opens up in the native maps app it takes me to a random location

Followed a video tutorial. When i build this app and hit the directions button it takes me to a random area instead of the coordinates provided. I am a beginner. Also, is there a way to pass in the locations address instead of coordinates, or should i just use the coordinates. Thanks for any responses. I am using Swift 5 in xCode 10. I changed the coordinate for privacy.
#IBAction func directionsClinic(_ sender: UIButton) {
let latitude:CLLocationDegrees = 38.465492
let longitude:CLLocationDegrees = 91.338905
let regionDistance:CLLocationDistance = 1000;
let coordinates = CLLocationCoordinate2DMake(latitude,
longitude)
let regionSpan = MKCoordinateRegion(center: coordinates,
latitudinalMeters: regionDistance, longitudinalMeters:
regionDistance)
let options = [MKLaunchOptionsMapCenterKey:
NSValue(mkCoordinate:regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan:
regionSpan.span)]
let placemark = MKPlacemark(coordinate: coordinates)
let mapItem = MKMapItem(placemark:placemark)
mapItem.openInMaps(launchOptions: options)
}
i have just tried a few different youtube videos guides, but most were a year+ old and im not sure if the code has changed
Expected the location of the coordinates to show up in the native iphone maps app, instead it was taking me to a place on the other side of the globe.
You can try this to open with a specific address:
let baseUrl: String = "http://maps.apple.com/?q="
let encodedName = theAddress.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) ?? ""
let finalUrl = baseUrl + encodedName
if let url = NSURL(string: finalUrl) {
UIApplication.shared.open(url)
}
The Maps app will intercept the request and open the app.

How to prevent Safari from launching when using MapLinks?

I am using the following code to launch Maps from within my project:
#IBAction func navigate(){
let mapLinksSchemeURL = URL(string: "http://maps.apple.com/?daddr=\(latitude),\(longitude)&t=s&dirflg=d")
UIApplication.shared.open(mapLinksSchemeURL!, options: [:], completionHandler: nil)
}
This code launches Safari first then it continues to launch Maps. This doesn't particularly look very refined. Is there a way to skip Safari and go straight to Maps?
You have an URL that´s why it goes to Safari before it recognises the type and goes to Apple Maps.
Use the following code instead to go straight to Apple Maps:
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 = "Start"
mapItem.openInMaps(launchOptions: options)

I want to open Google maps app with turn by turn directions with voice navigation in iOS

I want to open default google maps app with turn bu turn directions with voice navigation.
I have used the following code to open google maps app with source location and destination location. Google maps app opened fine and turn by turn directions are also working, but voice navigation is not working.
Please help me on this.
NSString* url = [NSString stringWithFormat: #"googlemaps://maps.google.com/maps?output=embed&saddr=%f,%f&daddr=%f,%f",[#"30.886537" doubleValue], [#"75.838870" doubleValue],[#"30.711423" doubleValue],[#"76.690839" doubleValue]];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:url]];
Please try with following function:
location = "(self.street!) (self.zip!) (self.city!) (self.country!)"
func showLocationPoints(location:String)
{
let geocoder:CLGeocoder = CLGeocoder()
geocoder.geocodeAddressString(location, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
}
else if let placemark = placemarks!.first
{
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let pointAnnotation:MKPointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = coordinates
pointAnnotation.title = "Apple HQ"
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01 , 0.01)
let region:MKCoordinateRegion = MKCoordinateRegionMake(coordinates, span)
self.mapView?.setRegion(region, animated: true)
self.mapView?.addAnnotation(pointAnnotation)
self.mapView?.centerCoordinate = coordinates
self.mapView?.selectAnnotation(pointAnnotation, animated: true)
print("Added annotation to map view")
let place = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem (placemark: place)
mapItem.name = location
let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: true]
MKMapItem.openMapsWithItems([mapItem], launchOptions: options as? [String : AnyObject])
}
})
}

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