Creating Overlay / Polygon Mapkit Swift 5



我试着做了一个Overlay,但在地图上什么都没有显示。

我想画4条线,做成一个正方形的形状,显示在地图上(我添加了4个CLLocationCoord(。

我做错了什么

我应该添加一些代码吗?

我试着添加mapView.delegate=self,但我不知道为什么它不起作用。

导入UIKit

导入MapKit

导入CoreLocation

class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!

let locationManager = CLLocationManager()
let regionInMeters: Double = 1000

override func viewDidLoad() {
super.viewDidLoad()
checkLocationServices()

//calling the method
addBoundry()

}
func addBoundry(){ //creation of a polygon
var points = [CLLocationCoordinate2DMake(52.284428, 20.989394),
CLLocationCoordinate2DMake(52.224534, 21.044326),
CLLocationCoordinate2DMake(52.209182, 20.948024),
CLLocationCoordinate2DMake(52.247143, 20.918842),]
let polygon = MKPolygon(coordinates: &points, count: points.count)
mapView.addOverlay(polygon)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolygon {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.strokeColor = .magenta
return polygonView
}
return MKOverlayRenderer()


}

func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest

}

func centerViewOnUserLocation () {
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters:  regionInMeters, longitudinalMeters: regionInMeters)
mapView.setRegion(region, animated: true)
}
}
func checkLocationServices() {
if   CLLocationManager.locationServicesEnabled() {
setupLocationManager()
checkLocationAuthorization()
} else {

// Show alert letting the user know they have to turn this on.

}
}
func checkLocationAuthorization() {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
mapView.showsUserLocation = true
centerViewOnUserLocation()
locationManager.startUpdatingLocation()
break
case .denied:
// Show alert instructing them how to turn on perm
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
// Show an alert letting them know what's up
break
case .authorizedAlways:
break

}
}

}
extension ViewController: CLLocationManagerDelegate {

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {return}
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
mapView.setRegion(region, animated: true)

}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAuthorization()
}
}
mapView.delegate = self

在类实现MKMapViewDelegate时工作。

类似的东西

class ViewController: UIViewController, MKMapViewDelegate {

最新更新