首页 > 解决方案 > 按下按钮后使用导航启动地图应用程序

问题描述

按下按钮时,我正在尝试使用导航自动打开地图应用程序。

我的 ViewController 看起来像这样:

import UIKit
import MapKit

class WhereViewController: UIViewController {


@IBOutlet weak var MapView: MKMapView!
@IBAction func navigateButtonHandler(_ sender: UIButton) {
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
        let location = view.annotation as! Artwork
        let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
        location.mapItem().openInMaps(launchOptions: launchOptions)
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    // set initial location in Honolulu
    let initialLocation = CLLocation(latitude: 21.282778, longitude: -157.829444)
    centerMapOnLocation(location: initialLocation)
    //MapView.delegate = self
    // show artwork on map
    let artwork = Artwork(title: "King David Kalakaua",
                          locationName: "Waikiki Gateway Park",
                          discipline: "Sculpture",
                          coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))
    MapView.addAnnotation(artwork)
}

let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                              regionRadius, regionRadius)
    MapView.setRegion(coordinateRegion, animated: true)
   }
}

我的艺术品 Swift 文件看起来像这样:

import Foundation
import MapKit
import Contacts

class Artwork: NSObject, MKAnnotation {
let title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D

init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.locationName = locationName
    self.discipline = discipline
    self.coordinate = coordinate

    super.init()
}

var subtitle: String? {
    return locationName
}

// Annotation right callout accessory opens this mapItem in Maps app
func mapItem() -> MKMapItem {
    let addressDict = [CNPostalAddressStreetKey: subtitle!]
    let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = title
    return mapItem
  }
}

当我按下按钮时,它不起作用。我的错误在哪里?希望您能够帮助我。我遵循 MapKit 的这些教程:

https://www.raywenderlich.com/548-mapkit-tutorial-getting-started

感谢您的回答

标签: iosswiftmapkit

解决方案


推荐阅读