今回はマップ上に点を打つやり方を共有します。
Storyboard
ViewController
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
setupMapView()
}
//MapViewの初期設定
private func setupMapView() {
let tapGestureRecognizer = UITapGestureRecognizer()
tapGestureRecognizer.addTarget(self, action: #selector(onTap(sender:)))
mapView.addGestureRecognizer(tapGestureRecognizer)
mapView.frame = view.bounds
mapView.delegate = self
view.addSubview(mapView)
}
//タップされた時のアクション (点を打つ)
@objc func onTap(sender: UITapGestureRecognizer) {
let tapPoint = sender.location(in: mapView)
let location = mapView.convert(tapPoint, toCoordinateFrom: mapView)
let circle = MKCircle(center: location, radius: 10000)
mapView.addOverlay(circle)
}
}
//MapViewDelegateの記述
extension ViewController: MKMapViewDelegate {
public func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let circle = overlay as? MKCircle {
let circleRenderer = MKCircleRenderer(circle: circle)
circleRenderer.strokeColor = .black
circleRenderer.fillColor = .black
circleRenderer.lineWidth = 1.5
return circleRenderer
}
return MKOverlayRenderer()
}
}
☆参考文献