MapViewのタップした箇所に黒丸を描画する
MapViewのタップした箇所に黒丸を描画する方法です。 タップした箇所に黒丸を描画しています。黒丸のサイズは地図に対して相対的ではなく絶対的(地図を拡大すると黒丸も大きくなる)になります。 相対的なものにしたいときはMKPointAnnotationを使うと良いかもしれません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import MapKit | |
class ViewController: UIViewController { | |
let mapView = MKMapView() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
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) | |
} | |
} | |
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 = 2.0 | |
return circleRenderer | |
} | |
return MKOverlayRenderer() | |
} | |
} |