Onur
Onur

Reputation: 247

How to show the direction between two locations on a map in Swift?

I am trying to show the direction between two locations in Swift. When my app launches, first it shows the current location and then I can see the city which I want on the map using a text field and a button. Now I am trying to show directions between current location and searched city.

Thanks to this function, I can see the city which I want on the map:

@IBAction func myButton(sender: AnyObject)
{
    let geoCoder = CLGeocoder()

    let addressString = myTextField.text

    geoCoder.geocodeAddressString(addressString, completionHandler:
        {(placemarks: [AnyObject]!, error: NSError!) in

            if error != nil
            {
                println("Geocode failed with error: \(error.localizedDescription)")
            }

            else if placemarks.count > 0
            {
                let placemark = placemarks[0] as! CLPlacemark
                let location = placemark.location

                self.mapControl(location.coordinate.latitude, longitude: location.coordinate.longitude)
            }
    })
}

This is my mapControl function which loads the city on the map:

func mapControl(latitude : Double, longitude : Double)
{
    var lastlocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

    let span = MKCoordinateSpanMake(3, 3)
    let region = MKCoordinateRegion(center: lastlocation, span: span)
    let regionRadius : CLLocationDistance = 1000
    mapView.setRegion(region, animated: true)
}

How can I show the direction between current location and searched city?

Upvotes: 1

Views: 4221

Answers (1)

Ethan Shea
Ethan Shea

Reputation: 50

In order to get directions, you actually have to fetch the route from Apple's maps' server using calculateDirectionsWithCompletionHandler.

First create the relevant MKMapItems for both the source and destination, e.g

let geocoder = CLGeocoder()
let location = CLLocation(latitude: sourceLatitude, longitude: sourceLongitude)

geocoder.reverseGeocodeLocation(location, completionHandler: {
    (placemarks:[AnyObject]?, error:NSError?) -> Void in
    if placemarks?.count > 0 {
        if let placemark: MKPlacemark = placemarks![0] as? MKPlacemark {
            self.source =  MKMapItem(placemark: placemark)
        }
    }
    })

You also want to repeat this for the destination

let request:MKDirectionsRequest = MKDirectionsRequest()

// source and destination are the relevant MKMapItems
request.setSource(source)
request.setDestination(destination)

// Specify the transportation type
request.transportType = MKDirectionsTransportType.Automobile;

// If you're open to getting more than one route, 
// requestsAlternateRoutes = true; else requestsAlternateRoutes = false;
request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)

directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in

    if error == nil {
    self.directionsResponse = response
    // Get whichever currentRoute you'd like, ex. 0
    self.route = directionsResponse.routes[currentRoute] as MKRoute
}
})

Then after retrieving the MKRoute, you can add the polyline to the map like so:

mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)

Doing this you will be able to show the direction between two locations in Swift. Just edit the code, accordingly.

Upvotes: 3

Related Questions