MKPointAnnotation为MKMapItem

时间:2019-01-12 02:49:33

标签: swift mapkit mkannotation mkmapitem

尝试打开Apple Maps以获得路线时出现错误“无法将'NSKVONotifying_MKPointAnnotation'类型的值转换为'MKMapItem'”。我是新手,我一直在拼凑代码以尝试使其正常工作。

struct Location {
    let agencyId: String
    let agencyEventId: String
    let agencyEventSubTypeCode: String
    let latitude: Double
    let longitude: Double
    let agencyEventTypeCode: String
}

func multiPoint() {

    for receivedEvent in receivedEventsList {
        mapEventLatitude = receivedEvent.latitude!
        mapEventLongitude = receivedEvent.longitude!
        latDouble = ("\(mapEventLatitude))" as NSString).doubleValue
        longDouble = ("\(mapEventLongitude))" as NSString).doubleValue
        multiMapAgencyEventSubTypeCode = receivedEvent.agencyEventSubtypeCode!
        multiMapAgencyId = receivedEvent.agencyId!
        multiMapAgencyEventId = receivedEvent.agencyEventId!
        multiMapAgencyEventTypeCode = receivedEvent.agencyEventTypeCode!

        let locations = [
            Location(agencyId: multiMapAgencyId, agencyEventId: multiMapAgencyEventId, agencyEventSubTypeCode: multiMapAgencyEventSubTypeCode, latitude: latDouble, longitude: longDouble, agencyEventTypeCode: multiMapAgencyEventTypeCode)
            ]


        for location in locations {
            let annotation = MKPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
            annotation.title = location.agencyId
            annotation.subtitle = multiMapAgencyEventSubTypeCode
            multiEventMap?.addAnnotation(annotation)
            eventTypeNumber = ("\(multiMapAgencyEventTypeCode))" as NSString).intValue
        }
    }
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let reuseIdentifier = "annotationView"
    let view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
        view.markerTintColor = UIColor.blue
        view.glyphText = "x"
        view.displayPriority = .required
        view.clusteringIdentifier = nil
        view.canShowCallout = true
        view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    return view
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    let location =  view.annotation as! MKMapItem
    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    location.openInMaps(launchOptions: launchOptions)
}

1 个答案:

答案 0 :(得分:0)

将注释添加到地图时,您将其添加为MKPointAnnotation,因此投射到MKMapItem的操作显然会失败。

我建议不要创建MKPointAnnotation或创建自己的MKPlacemark子类,而不要创建MKPlacemark,其中应包含您感兴趣的其他属性。 calloutAccessoryControlTapped可以

  • view.annotation投射到您的地标类型;
  • 使用该地标创建一个MKMapItem;然后
  • mapItem.openInMaps(launchOptions:)