如何在Swift中创建MKCircle? [英] How to create MKCircle in Swift?

查看:120
本文介绍了如何在Swift中创建MKCircle?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Iv been searching all around for a good explanation of how to make an MKCircle annotation for the MapView using Swift 2.0 but I cant seem to find an adequate explanation. Can someone post some example code showing how to create the MKCircle annotation? Here is the code i'm using to make the map and get the coordinate.

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

推荐答案

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

Will show step wise approach about how to create a circular overlay on map view using swift 3 with xcode 8.3.3

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

In your main storyboard file drag map kit view on to the scene(view) of storyboard and create outlet for the same, here i created mapView. Also you want to create overlay dynamically whenever you go for long press on map, so drag Long Press Gesture Recognizer on to the mapView from object libary and then create action method for the same, here i had created addRegion() for the same.

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

  1. create a global constant for CLLocationManager class so that it can be accessed in every function. And in your viewDidLoad method, add some code for getting authorization from the user.

    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()

        }

  • 添加代码,以便在长按手势识别器操作方法addRegion()中执行长按手势识别器时生成圆形区域.

  • Add code for generating a circular region whenever you do long press gesture recognizer in your long press gesture recognizer action method 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的委托.

    Still you won't see circle physically on the map until you render circle on map. for this you need to implement delegate of mapviewdelegate.

            func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {}
    

    1. 为使代码看起来更简洁,您可以在类结束的最后大括号后创建扩展.一个扩展包含CLLocationManagerDelegate的代码,另一个包含MKMapViewDelegate的代码.

    1. To make code look more cleaner you can create extension after last brace where your class ends. One extension contains code for CLLocationManagerDelegate and other for MKMapViewDelegate.

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

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

    you should call locationManager.stopUpdatingLocation() in delegate method so that your battery does not drain out.

            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
                }
            }
    

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

    Here we are making the actual circle on the screen.

    最终代码应如下所示.

    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
        }
    }
    

    这篇关于如何在Swift中创建MKCircle?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆