如何在Swift中显示地图上两个位置之间的方向?

时间:2015-05-01 11:05:28

标签: swift mapkit direction

我试图在Swift中显示两个位置之间的方向。当我的应用程序启动时,首先显示当前位置,然后我可以使用文本字段和按钮在地图上查看我想要的城市。现在我试图显示当前位置和搜索城市之间的路线。

感谢这个功能,我可以在地图上看到我想要的城市:

@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)
            }
    })
}

这是我的mapControl功能,用于在地图上加载城市:

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)
}

如何显示当前位置和搜索到的城市之间的方向?

1 个答案:

答案 0 :(得分:3)

为了获取路线,您实际上必须使用 calculateDirectionsWithCompletionHandler从Apple的地图服务器获取路线。

首先为源和目标创建相关的MKMapItems,例如

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)
        }
    }
    })

您还想为目的地重复此操作

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
}
})

然后在检索 MKRoute 后,您可以将折线添加到地图中,如下所示:

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

执行此操作,您将能够在Swift中显示两个位置之间的方向。只需编辑代码即可。