Mapkit получить текущие координаты метки - PullRequest
0 голосов
/ 21 марта 2019

Я довольно новичок в MapKit и пытаюсь показать информацию и указания, как только маркер места выбран.Я показываю местные больницы и службы скорой помощи.Как получить информацию о выбранной в данный момент метке.Я хочу, чтобы можно было показать несколько строк информации о выбранном маркере.Например, имя, адрес, номер телефона и, возможно, кнопка для направления.Я хочу сохранить текущие выбранные координаты маркеров в переменную.

карты изображения

class MapKitViewController: UIViewController, MKMapViewDelegate {


let locationManager = CLLocationManager()
let regionInMeters: Double = 10000
var previousLocation: CLLocation?

let geoCoder = CLGeocoder()
var directionsArray: [MKDirections] = []



func setupLocationManager() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
}

func centerViewOnUserLocation() {
    if let location = locationManager.location?.coordinate {
        let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)
    }
}


func checkLocationServices() {
    if CLLocationManager.locationServicesEnabled() {
        setupLocationManager()
        performSearch()
        checkLocationAuthorization()
    } else {
        // Show alert letting the user know they have to turn this on.
    }
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation)
    -> MKAnnotationView? {

        let identifier = "marker"
        var view: MKMarkerAnnotationView

        if let dequeuedView = mapView.dequeueReusableAnnotationView(
            withIdentifier: identifier)
            as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view =
                MKMarkerAnnotationView(annotation: annotation,
                                       reuseIdentifier: identifier)


            view.markerTintColor = UIColor.blue
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

        }
        return view
}

func mapView(_: MKMapView, annotationView:
    MKAnnotationView, calloutAccessoryControlTapped: UIControl) {


    print("Control tapped")
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {


}

1 Ответ

0 голосов
/ 21 марта 2019

Исходный класс аннотаций (MKPointAnnotation) не позволяет вам дать много информации помимо заголовка и субтитров. Таким образом, вам нужно сделать подкласс из MKPointAnnotation, чтобы вы могли однозначно идентифицировать штырь, по которому нажимает пользователь, который будет обнаружен с помощью didSelect * делегированного метода.

Сначала создайте файл swift с именем MyPointAnnotation следующим образом.

import MapKit

class MyPointAnnotation: MKPointAnnotation {
    var identifier: String?
    //var image: UIImage?
    var lat: Double!
    var lon: Double!
}

Затем используйте указанный выше подкласс, чтобы делать аннотации и добавлять их на карту.

import UIKit
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate {
    // MARK: - Variables

    // MARK: - IBOutlet
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
    }

    @IBAction func addNewPin(_ sender: UIBarButtonItem) {
        addNewAnnotationPin(title: "Restaurant", subTitle: "Barbecue", lat: 35.6387264874361, lon: 139.99950350000003)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard !(annotation is MKUserLocation) else {
            return nil
        }

        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        if pinView == nil {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            pinView?.pinTintColor = UIColor.red
            pinView?.canShowCallout = true
        }
        else {
            pinView?.annotation = annotation
        }
        return pinView
    }

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        if view.annotation is MyPointAnnotation {
            if let selectedAnnotation = view.annotation as? MyPointAnnotation {
                if let id = selectedAnnotation.identifier {
                    for pin in mapView.annotations as! [MyPointAnnotation] {
                        if let myIdentifier = pin.identifier {
                            if myIdentifier == id {
                                print(pin.lat ?? 0.0)
                                print(pin.lon ?? 0.0)
                            }
                        }
                    }
                }
            }
        }
    }

    func addNewAnnotationPin(title: String, subTitle: String, lat: Double, lon: Double) {
        let myPin = MyPointAnnotation()
        myPin.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        myPin.title = title
        myPin.subtitle = subTitle
        myPin.identifier = UUID().uuidString
        myPin.lat = lat
        myPin.lon = lon
        self.mapView.addAnnotation(myPin)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...