ios 在 swift 中长按时向地图视图添加图钉注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30858360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:26:44  来源:igfitidea点击:

Adding a pin annotation to a map view on a long press in swift

iosswiftannotationsmapsmkmapview

提问by Matt Spoon

I'm trying to make an iPhone app which requires users to be able to long press on a place on a map view to drop a pin there. Does anybody know how this is done?

我正在尝试制作一个 iPhone 应用程序,它要求用户能够长按地图视图上的某个位置以在那里放置图钉。有人知道这是怎么做的吗?

The behaviour is observable in apple maps when you long press on the screen. It will drop a pin and present an annotation saying "dropped pin"

当您长按屏幕时,在苹果地图中可以观察到这种行为。它将掉落一个大头针并显示一个注释,上面写着“掉下的大头针”

采纳答案by Josh Hamet

1) Instantiate a UILongPressGestureRecognizerand add it to the MKMapView.

1) 实例化 aUILongPressGestureRecognizer并将其添加到MKMapView.

2) When the selector gets called after the user has a long press, call the addAnnotation methodin MKMapViewwith the appropriate title and coordinate.

2)当用户有一长按之后的选择器被调用,调用addAnnotation方法MKMapView用适当的标题和坐标。

3) Then make sure you conform to the MKMapViewDelegateand implement viewForAnnotation:which will be called right after you add the annotation and return a MKPinAnnotationView

3)然后确保您符合将在添加注释并返回后立即调用的MKMapViewDelegate和实现viewForAnnotation:MKPinAnnotationView

回答by itzhar

  1. add UILongPressGestureRecognizerto your MapView

    var uilgr = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
    uilgr.minimumPressDuration = 2.0
    
    map.add (uilgr)
    
    //IOS 9
    map.addGestureRecognizer(uilgr) 
    
  2. Add annotation on Long press detect - func:

    func addAnnotation(gestureRecognizer:UIGestureRecognizer){
        if gestureRecognizer.state == UIGestureRecognizerState.Began {
            var touchPoint = gestureRecognizer.locationInView(map)
            var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
            let annotation = MKPointAnnotation()
            annotation.coordinate = newCoordinates
    
            CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude), completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    println("Reverse geocoder failed with error" + error.localizedDescription)
                    return
                }
    
            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
    
                // not all places have thoroughfare & subThoroughfare so validate those values
                annotation.title = pm.thoroughfare + ", " + pm.subThoroughfare
                annotation.subtitle = pm.subLocality
                self.map.addAnnotation(annotation)
                println(pm)
            }
            else {
                annotation.title = "Unknown Place"
                self.map.addAnnotation(annotation)
                println("Problem with the data received from geocoder")
            }
            places.append(["name":annotation.title,"latitude":"\(newCoordinates.latitude)","longitude":"\(newCoordinates.longitude)"])
        })
    }
    }
    
  3. or you can add annotation without any title:

    func action(gestureRecognizer:UIGestureRecognizer){
        var touchPoint = gestureRecognizer.locationInView(map)
        var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
        let annotation = MKPointAnnotation()
        annotation.coordinate = newCoordinates
        map.addAnnotation(annotation)
    }
    
  1. 添加UILongPressGestureRecognizer到您的 MapView

    var uilgr = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
    uilgr.minimumPressDuration = 2.0
    
    map.add (uilgr)
    
    //IOS 9
    map.addGestureRecognizer(uilgr) 
    
  2. 在长按检测上添加注释 - 功能:

    func addAnnotation(gestureRecognizer:UIGestureRecognizer){
        if gestureRecognizer.state == UIGestureRecognizerState.Began {
            var touchPoint = gestureRecognizer.locationInView(map)
            var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
            let annotation = MKPointAnnotation()
            annotation.coordinate = newCoordinates
    
            CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude), completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    println("Reverse geocoder failed with error" + error.localizedDescription)
                    return
                }
    
            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
    
                // not all places have thoroughfare & subThoroughfare so validate those values
                annotation.title = pm.thoroughfare + ", " + pm.subThoroughfare
                annotation.subtitle = pm.subLocality
                self.map.addAnnotation(annotation)
                println(pm)
            }
            else {
                annotation.title = "Unknown Place"
                self.map.addAnnotation(annotation)
                println("Problem with the data received from geocoder")
            }
            places.append(["name":annotation.title,"latitude":"\(newCoordinates.latitude)","longitude":"\(newCoordinates.longitude)"])
        })
    }
    }
    
  3. 或者您可以添加没有任何标题的注释:

    func action(gestureRecognizer:UIGestureRecognizer){
        var touchPoint = gestureRecognizer.locationInView(map)
        var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
        let annotation = MKPointAnnotation()
        annotation.coordinate = newCoordinates
        map.addAnnotation(annotation)
    }
    

回答by oscar castellon

First declare UIGestureRecognizerin viewDidLoad

首先声明UIGestureRecognizerviewDidLoad

let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(addWaypoint(longGesture:)))
mapView.addGestureRecognizer(longGesture)

Second add the function for longPress

二、为longPress添加功能

@objc func addWaypoint(longGesture: UIGestureRecognizer) {

    let touchPoint = longGesture.location(in: mapView)
    let wayCoords = mapView.convert(touchPoint, toCoordinateFrom: mapView)
    let location = CLLocation(latitude: wayCoords.latitude, longitude: wayCoords.longitude)
    myWaypoints.append(location)

    let wayAnnotation = MKPointAnnotation()
    wayAnnotation.coordinate = wayCoords
    wayAnnotation.title = "waypoint"
    myAnnotations.append(wayAnnotation)
}

I recommend creating the annotations in an array that will serve you later if you want to delete it, like this...

我建议在一个数组中创建注释,如果你想删除它,稍后将为你服务,就像这样......

var myAnnotations = [MKPointAnnotation]()

If you have different annotations, you can delete only the annotations you want, for that when you add a new annotation add to the array. To delete only one group of annotations just do the following

如果您有不同的注释,您可以只删除您想要的注释,因为当您添加新注释时将其添加到数组中。要仅删除一组注释,只需执行以下操作

for dots in myAnnotations{
    mapView.removeAnnotation(dots)
}

To delete all annotations try

要删除所有注释,请尝试

mapView.removeAnnotations(mapView.annotations)

Apologies for the translation....

为翻译道歉......

回答by K. Sergey

Update Swift3

更新 Swift3

func action(gestureRecognizer:UIGestureRecognizer){
    let touchPoint = gestureRecognizer.location(in: mapView)
    let newCoordinates = mapView.convert(touchPoint, toCoordinateFrom: mapView)
    let annotation = MKPointAnnotation()
    annotation.coordinate = newCoordinates
    mapView.addAnnotation(annotation)
}