Как сделать, чтобы аннотация появлялась на карте Apple через Swift? - PullRequest
0 голосов
/ 24 января 2019

Так что, в основном, я вызываю API отдыха, чтобы получить все местоположения автобусных остановок, а затем помещаю аннотации всех автобусных остановок в пределах 5 км от моего текущего местоположения на карте при вызове кнопки. Тем не менее, это просто не отображается, я не могу понять проблему.

импорт UIKit импорт MapKit

class MapKitViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var GPSButton: UIButton!
var stopSearchResults: [Value] = []
var Annotations: [BusStopAnnotation] = []
let queryServices = QueryService()
let locationManager:CLLocationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
var currentLocation: CLLocationCoordinate2D?
var counter: Int = 0
override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.isNetworkActivityIndicatorVisible = true
    queryServices.GetAllBusStops(){
            result in
        UIApplication.shared.isNetworkActivityIndicatorVisible  = false
        if let result = result {
            self.stopSearchResults = result.value
        }
    }
    configureLocationService()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}




private func configureLocationService() {
    locationManager.delegate = self
    let status = CLLocationManager.authorizationStatus()

    if status == .notDetermined {
        locationManager.requestAlwaysAuthorization()
    } else if status == .authorizedAlways || status == .authorizedWhenInUse {
        beginLocationUpdate(locationManager: locationManager)
    }

}

private func beginLocationUpdate(locationManager: CLLocationManager) {
    mapView.showsUserLocation = true
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}

private func zoomToLatestLocation(with coordinate: CLLocationCoordinate2D) {
    let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
    mapView.setRegion(zoomRegion, animated: true)
}


@IBAction func GPSTrack(_ sender: Any) {
    InputAllAnnotation(busStops: stopSearchResults)
    print("Searching for nearby bus stops")
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("Did get latest location")

    guard let latestLocation = locations.first else { return }
    if currentLocation  == nil {
        zoomToLatestLocation(with: latestLocation.coordinate)
    }

    currentLocation = latestLocation.coordinate
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print("The status changed")
    if status == .authorizedAlways || status == .authorizedWhenInUse {
        beginLocationUpdate(locationManager: manager)
    }
}

func InputAllAnnotation(busStops: [Value]) {
    for busStop in busStops{
        let busStopObj = BusStopAnnotation(value: busStop)
        Annotations.append(busStopObj)

        let distance = busStop.GetDistance(latitude: Double(currentLocation?.latitude ?? 0), longitude: Double(currentLocation?.longitude ?? 0))
        if  distance < 5000 {
            mapView.addAnnotation(busStopObj)
        }
    }
}

}

расширение MapKitViewController: MKMapViewDelegate { func mapView (_ mapView: MKMapView, viewFor аннотация: MKAnnotation) -> MKAnnotationView? {

    if let busStopAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) as?
        MKMarkerAnnotationView {
        busStopAnnotation.animatesWhenAdded = true
        busStopAnnotation.titleVisibility = .adaptive
        busStopAnnotation.canShowCallout = true
        return busStopAnnotation
    }

    return nil
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("The annotation was selected: \(String(describing: view.annotation?.title))")
}

}

конечный класс BusStopAnnotation: NSObject, MKAnnotation { координата var: CLLocationCoordinate2D var title: String? var subtitle: String? var busStopCode: String?

init(value : Value) {
    self.coordinate = value.GetLocationCoordinate2D()
    self.title = value.roadName
    self.subtitle = value.description
    self.busStopCode = value.busStopCode
}
init(coordinate: CLLocationCoordinate2D, roadName: String?, description: String?, busStopCode: String?) {
    self.coordinate = coordinate
    self.title = roadName
    self.subtitle = description
    self.busStopCode = busStopCode
}

var region: MKCoordinateRegion {
    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    return MKCoordinateRegion(center: coordinate, span: span)
}

}

Ответы [ 2 ]

0 голосов
/ 25 января 2019

импорт:

import UIKit
import MapKit

установка класса

class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

на вашей карте

@IBOutlet weak var map: MKMapView!

Код:

let customPin : CLLocationCoordinate2D = CLLocationCoordinate2DMake(Latitude, Longitude)
    let objectAnnotation = MKPointAnnotation()
    objectAnnotation.coordinate = customPin

    objectAnnotation.title = "Here's your custom PIN"
    self.map.addAnnotation(objectAnnotation)

дополнительно:

для установки камеры рядом с PIN-кодом

let theSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.009, longitudeDelta: 0.009)
        let pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(Latitude, Longitude)
        let region:MKCoordinateRegion = MKCoordinateRegion(center: pointLocation, span: theSpan)
        self.map.setRegion(region, animated: true)

перемещение значений в зависимости от того, насколько близко / далеко вы хотите установить камеру

let theSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: HERE, longitudeDelta: HERE)
0 голосов
/ 24 января 2019

Вам может понадобиться

self.mapView.delegate = self
...