首页 > 解决方案 > 如何通过 Swift 使注解出现在 Apple 地图上?

问题描述

所以基本上,我正在调用一个 Rest API 来获取所有巴士站的位置,然后在调用按钮时将距离我当前位置 5 公里内的所有巴士站的注释放在地图上。但是,它只是没有显示,我似乎无法找出问题所在。

import UIKit
import 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)
            }
        }
    }
    
}


extension MapKitViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: 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))")
    }

}


final class BusStopAnnotation: NSObject, MKAnnotation {
    var coordinate: 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)
    }
}

标签: iosswiftmkmapviewmkannotationmkannotationview

解决方案


你可能需要

self.mapView.delegate = self

推荐阅读