一尘不染

如何在Swift中创建MKCircle?

swift

我一直在四处搜寻有关如何使用Swift
2.0为MapView制作MKCircle注释的良好解释,但我似乎找不到足够的解释。有人可以张贴一些示例代码来显示如何创建MKCircle批注吗?这是我用来制作地图并获取坐标的代码。

let address = self.location

let geocoder = CLGeocoder()

    geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
        if((error) != nil){
            print("Error", error)
        }
        if let placemark = placemarks?.first {
            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

            self.locationCoordinates = coordinates
            let span = MKCoordinateSpanMake(0.005, 0.005)
            let region = MKCoordinateRegion(center: self.locationCoordinates, span: span)
            self.CIMap.setRegion(region, animated: true)

            let annotation = MKPointAnnotation()
            annotation.coordinate = self.locationCoordinates
            self.CIMap.addAnnotation(annotation)

            self.CIMap.layer.cornerRadius = 10.0

            self.CIMap.addOverlay(MKCircle(centerCoordinate: self.locationCoordinates, radius: 1000))
        }
    })

阅读 283

收藏
2020-07-07

共1个答案

一尘不染

将展示有关如何使用xcode 8.3.3的swift 3在地图视图上创建圆形叠加层的分步方法

在您的主故事板文件中,将地图工具包视图拖到故事板的场景(视图)上,并为其创建出口,在这里我创建了mapView。另外,您还希望在地图上长按时动态创建叠加层,因此将“长按手势识别器”从对象库拖动到mapView上,然后为其创建动作方法,这里我为该对象创建了addRegion()。

  1. 为CLLocationManager类创建一个全局常量,以便可以在每个函数中对其进行访问。在您的viewDidLoad方法中,添加一些代码以获取用户授权。

        import UIKit  
    import MapKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var mapView: MKMapView!
        let locationManager = CLLocationManager()
    
    override func viewDidLoad() {  
            super.viewDidLoad()
    
            locationManager.delegate = self
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
    
        }
    
  2. 只要在长按手势识别器操作方法addRegion()中执行长按手势识别器,就添加用于生成圆形区域的代码。

        @IBAction func addRegion(_ sender: Any) {  
            print("addregion pressed")  
            guard let longPress = sender as? UILongPressGestureRecognizer else {return}
    
            let touchLocation = longPress.location(in: mapView)
            let coordinates = mapView.convert(touchLocation, toCoordinateFrom: mapView)
            let region = CLCircularRegion(center: coordinates, radius: 5000, identifier: "geofence")
            mapView.removeOverlays(mapView.overlays)
            locationManager.startMonitoring(for: region)
            let circle = MKCircle(center: coordinates, radius: region.radius)
            mapView.add(circle)
    
        }
    

除非您在地图上渲染圆圈,否则您仍然不会在地图上实际看到圆圈。为此,您需要实现mapviewdelegate的委托。

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {}
  1. 为了使代码看起来更简洁,您可以在类结束的最后大括号后创建扩展。一个扩展包含CLLocationManagerDelegate的代码,另一个包含MKMapViewDelegate的代码。
        extension ViewController: CLLocationManagerDelegate {
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            locationManager.stopUpdatingLocation()
            mapView.showsUserLocation = true
        }
    }
    

您应该在委托方法中调用locationManager.stopUpdatingLocation(),以免电池电量耗尽。

        extension ViewController: MKMapViewDelegate {
            func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
                guard let circelOverLay = overlay as? MKCircle else {return MKOverlayRenderer()}

                let circleRenderer = MKCircleRenderer(circle: circelOverLay)
                circleRenderer.strokeColor = .blue
                circleRenderer.fillColor = .blue
                circleRenderer.alpha = 0.2
                return circleRenderer
            }
        }

在这里,我们在屏幕上绘制实际的圆。

最终代码应如下所示。

import UIKit
import MapKit

class ViewController: UIViewController {


    @IBOutlet var mapView: MKMapView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

    }

    // MARK: Long Press Gesture Recognizer Action Method

    @IBAction func addRegion(_ sender: Any) {
        print("addregion pressed")
        guard let longPress = sender as? UILongPressGestureRecognizer else {return}

        let touchLocation = longPress.location(in: mapView)
        let coordinates = mapView.convert(touchLocation, toCoordinateFrom: mapView)
        let region = CLCircularRegion(center: coordinates, radius: 5000, identifier: "geofence")
        mapView.removeOverlays(mapView.overlays)
        locationManager.startMonitoring(for: region)
        let circle = MKCircle(center: coordinates, radius: region.radius)
        mapView.add(circle)

    }

}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationManager.stopUpdatingLocation()
        mapView.showsUserLocation = true
    }
}

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        guard let circelOverLay = overlay as? MKCircle else {return MKOverlayRenderer()}

        let circleRenderer = MKCircleRenderer(circle: circelOverLay)
        circleRenderer.strokeColor = .blue
        circleRenderer.fillColor = .blue
        circleRenderer.alpha = 0.2
        return circleRenderer
    }
}
2020-07-07