プログラミング学習中のものです。皆様お忙しいとは思いますが、アドバイスがいただけるとありがたいです。
何卒、よろしくお願いいたします。
1、やりたいこと
swiftでmapkitを使用して、地図上を長押ししたところの座標をとり、そこを中心とした円を描こうとしています。
2.、起きている問題
swift学習中なのですが、いろいろなウェブページを参考にしつつ、試行錯誤しております。
長押しすると、地図上にピンを立てるプログラミングはできました。
円を地図上に表示するプログラミングもできました。
その二つを組み合わせて、今回のプログラミングを書いてみたのですが、狙い通りにいきません。
エラーメッセージは出ていませんし、シミュレーターでビルドできるのですが、長押ししても円を描けません。
3、参考にしたページ
下記のページを参考にしました。
https://faboplatform.github.io/SwiftDocs/3.mapkit/012_map/
https://hajihaji-lemon.com/swift/polygon_circle/
https://faboplatform.github.io/SwiftDocs/3.mapkit/006_pin/
- 関連するソースコードやスクリーンショット
下記が、実際に打ったコードになります。
swift
1// 2// ViewController.swift 3// enn$pin220618 4// 5// Created by USER on 2022/06/17. 6// 7 8import UIKit 9import MapKit 10 11class ViewController: UIViewController, MKMapViewDelegate { 12 13 let mapView = MKMapView() 14 15 override func viewDidLoad() { 16 super.viewDidLoad() 17 // Do any additional setup after loading the view. 18 //地図を表示 19 view.addSubview(mapView) 20 mapView.frame = CGRect(x: 20, y: 50, width: view.frame.self.width-40, height: view.frame.size.height-220) 21 // 長押しのUIGestureRecognizerを生成. 22 let myLongPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer() 23 myLongPress.addTarget(self, action: #selector(ViewController.recognizeLongPress(sender:))) 24 // MapViewにUIGestureRecognizerを追加. 25 mapView.addGestureRecognizer(myLongPress) 26 } 27 28 @objc func recognizeLongPress(sender: UILongPressGestureRecognizer) { 29 // 長押しした地点の座標を取得. 30 let location = sender.location(in: mapView) 31 // locationをCLLocationCoordinate2Dに変換. 32 let myCoordinate: CLLocationCoordinate2D = mapView.convert(location, toCoordinateFrom: mapView) 33 // 円を描画する(半径1000m). 34 let myCircle: MKCircle = MKCircle(center: myCoordinate, radius: CLLocationDistance(1000)) 35 // mapViewにcircleを追加. 36 mapView.addOverlay(myCircle) 37 } 38 override func didReceiveMemoryWarning() { 39 super.didReceiveMemoryWarning() 40 } 41 42 /* 43 addOverlayした際に呼ばれるデリゲートメソッド. 44 */ 45 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { 46 47 // rendererを生成. 48 let myCircleView: MKCircleRenderer = MKCircleRenderer(overlay: overlay) 49 50 // 円の内部を赤色で塗りつぶす. 51 myCircleView.fillColor = UIColor.red 52 53 // 円周の線の色を黒色に設定. 54 myCircleView.strokeColor = UIColor.black 55 56 // 円を透過させる. 57 myCircleView.alpha = 0.5 58 59 // 円周の線の太さ. 60 myCircleView.lineWidth = 1.5 61 62 return myCircleView 63 } 64} 65
回答1件
あなたの回答
tips
プレビュー