如何通过 Swift 使注解出现在 Apple 地图上?

Posted

技术标签:

【中文标题】如何通过 Swift 使注解出现在 Apple 地图上?【英文标题】:How to make the annotation appear on the Apple map via Swift? 【发布时间】:2019-06-18 14:24:50 【问题描述】:

所以基本上,我正在调用一个 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)
    

【问题讨论】:

您的问题中有太多代码。你应该把它减少到minimal reproducible example。 【参考方案1】:

你可能需要

self.mapView.delegate = self

【讨论】:

【参考方案2】:

导入:

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)

【讨论】:

以上是关于如何通过 Swift 使注解出现在 Apple 地图上?的主要内容,如果未能解决你的问题,请参考以下文章

Swift:如何使选项卡视图控制器按钮不显示?

如何在 iOS Objective-C 中集成“使用 Apple 登录”流程?

当Apple从设置中删除时,如何在Xcode 9 Simulator中访问Twitter?

在 Swift 里安全管理指针

如何在 Swift 中使用 Apple 地图 - 你必须使用 C 还是 Swift 可以?

如何使我在 UIAlertController 内的 UITextField 中输入的数据通过 Swift 中的重置持续存在?