如何在当前位置,MapKit,Swift,iOS10上绘制图钉注释

时间:2016-11-24 08:34:48

标签: ios objective-c swift annotations

我在故事板上有一个MapView,其中选中了User Location选项。我还写了一些代码来在地图上绘制另一个注释。此注释的坐标(tappedCoordinates)是从已注册的手势派生的。

//add new annotation
let annotation = MKPointAnnotation()
annotation.coordinate = tappedCoordinates
mapView.addAnnotation(annotation)

//add circle radius
let circle = MKCircle(center: tappedCoordinates, radius: 20)
mapView.setRegion(MKCoordinateRegion(center: tappedCoordinates, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)), animated: true)
mapView.add(circle)

此代码允许用户在地图上绘制注释(图钉)。它工作正常,除非用户尝试在其当前位置绘制注释。相反,MapView认为您选择了当前位置注释,并显示"当前位置"而不是允许用户绘制自定义注释。

如何停止用户位置注释的可点击性,并允许我的自定义注释放在同一区域?我不想删除当前位置注释。

2 个答案:

答案 0 :(得分:0)

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locObject = locations.last
    let annotation = MKPointAnnotation()
    let centerCoordinate = locObject?.coordinate
    annotation.coordinate = centerCoordinate!
    annotation.title = "Title"
    mapView.addAnnotation(annotation)

}

答案 1 :(得分:0)

class ViewController: UIViewController, MKMapViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    // Set map view delegate with controller
    self.mapView.delegate = self
}
}

覆盖其委托方法:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
    return nil
}

if (annotation.isKindOfClass(CustomAnnotation)) {
    let customAnnotation = annotation as? CustomAnnotation
    mapView.translatesAutoresizingMaskIntoConstraints = false
    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("CustomAnnotation") as MKAnnotationView!

    if (annotationView == nil) {
        annotationView = customAnnotation?.annotationView()
    } else {
        annotationView.annotation = annotation;
    }

    self.addBounceAnimationToView(annotationView)
    return annotationView
} else {
    return nil
}
}

//添加图钉(MKPointAnnotation)

override func viewDidLoad() {
super.viewDidLoad()

// Set map view delegate with controller
self.mapView.delegate = self

let newYorkLocation = CLLocationCoordinate2DMake(40.730872, -74.003066)
// Drop a pin
let dropPin = MKPointAnnotation()
dropPin.coordinate = newYorkLocation
dropPin.title = "USA"
mapView.addAnnotation(dropPin)
}