如何在 Swift 中使用 MapKit 绘制两个位置之间的路线?

iosiphone/ipadmobile developmentswift更新于 2026/3/2 16:07:17

要在地图上绘制两个位置之间的路线,我们需要这两个位置的坐标。

获得这两个位置的坐标后,我们就可以使用下面的函数在地图上显示两点之间的连线。在本例中,我将使用两个随机位置作为两个点。

func getDirections(loc1: CLLocationCoordinate2D, loc2: CLLocationCoordinate2D) {
   let source = MKMapItem(placemark: MKPlacemark(coordinate: loc1))
   source.name = "Your Location"
   let destination = MKMapItem(placemark: MKPlacemark(coordinate: loc2))
   destination.name = "Destination"
   MKMapItem.openMaps(with: [source, destination], launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}

在本教程中,我们将在 ViewDidLoad 中调用此函数来显示结果,但您可以根据需要使用它。

在此之前,我们必须创建两个位置。

override func viewDidLoad() {
   super.viewDidLoad()
   let coordinateOne = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 40.586746)!, longitude: CLLocationDegrees(exactly: -108.610891)!)
   let coordinateTwo = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 42.564874)!, longitude: CLLocationDegrees(exactly: -102.125547)!)
   self.getDirections(loc1: coordinateOne, loc2: coordinateTwo)
}

在设备上运行上述代码时,会得到以下输出



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部