按下按钮后启动带有导航的Map App

时间:2018-08-25 21:03:34

标签: ios swift mapkit

我试图在按下按钮时自动打开带有导航功能的Maps应用。

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

我的Artwork 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

感谢您的回答

0 个答案:

没有答案