我正在尝试复制我在另一个使用仅使用代码的故事板的项目中所拥有的内容。我正在努力的视图控制器是地图视图控制器。
我正在尝试创建一个显示用户位置的地图,在启动时缩放到该位置周围的合适级别,然后允许用户在地图上放置一个图钉,该图钉的周围会有一个圆圈覆盖销。
我已设法创建地图并显示用户位置,但我正在努力设置区域以在地图启动时放大位置。我一直在努力解决这个问题。
我知道我需要在某个地方使用CLlocation2D,但我不知道目前在哪里/如何使用它。
我还尝试使用函数来设置我的地图,到目前为止,代码是下面的(这是来自不同来源的一个试图让它符合我的目标的拙劣工作,所以如果它很混乱就道歉)
> import UIKit
> import MapKit
> import CoreLocation
>
> class MapViewController: UIViewController, MKMapViewDelegate,
> CLLocationManagerDelegate {
> var mapView: MKMapView!
> var locationManager = CLLocationManager()
>
> override func viewDidLoad() {
> super.viewDidLoad()
>
> setupMapView()
>
> }
>
> override func viewWillAppear(_ animated: Bool) {
> super.viewWillAppear(animated)
>
> }
>
> func setupMapView() {
> let mapView = MKMapView()
>
> let leftMargin:CGFloat = 0
> let topMargin:CGFloat = 0
> let mapWidth:CGFloat = view.frame.size.width
> let mapHeight:CGFloat = view.frame.size.height
>
> mapView.frame = CGRect(x: leftMargin, y: topMargin, width: mapWidth, height: mapHeight)
>
> mapView.mapType = MKMapType.standard
> mapView.isZoomEnabled = true
> mapView.isScrollEnabled = true
> mapView.showsCompass = true
> mapView.showsScale = true
> mapView.showsUserLocation = true
>
> let noLocation = CLLocationCoordinate2D()
> let span:MKCoordinateSpan = MKCoordinateSpanMake(0.05, 0.05)
> let viewLocation = MKCoordinateRegionMake(noLocation, span)
>
>
> mapView.setRegion(viewLocation, animated: true)
> print(viewLocation)
>
> view.addSubview(mapView)
> }
>
> //add function to create circle overlay
>
> // override func didReceiveMemoryWarning() { //
> super.didReceiveMemoryWarning() // // Dispose of any resources
> that can be recreated. // }
>
>
> /*
> // MARK: - Navigation
>
> // In a storyboard-based application, you will often want to do a little preparation before navigation
> override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
> // Get the new view controller using segue.destinationViewController.
> // Pass the selected object to the new view controller.
> }
> */
>
> }
对于引脚,在我使用的故事板中
@IBAction func pinDrop(_ sender:UILongPressGestureRecognizer)
但我不确定如何将其转换为程序代码。
任何帮助都会很棒!
答案 0 :(得分:0)
像这样添加长按
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.addAnnotation(_:)))
self.mapView.addGestureRecognizer(longPress)
//
获取按
的坐标@objc func addAnnotation(_ gestureRecognizer:UIGestureRecognizer)
{
if gestureRecognizer.state != UIGestureRecognizerState.began
{
return
}
let touchPoint = gestureRecognizer.location(in: self.mapView)
let newCoordinates = self.mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
}
//
let noLocation = self.mapView.userLocation.coordinate
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.05, 0.05)
let viewLocation = MKCoordinateRegionMake(noLocation, span)
mapView.setRegion(viewLocation, animated: true)