繁体   English   中英

如何使用UILongPressGestureRecognizer在用户位置添加图钉?

[英]How can I use a UILongPressGestureRecognizer to add pin on user location?

我正在制作一个在地图上添加图钉的应用程序,到目前为止,它一直在用户长按的位置添加图钉,但是我希望它可以更改并添加到用户位置,但是,我不知道不知道要进行哪些更改才能使其实现,请您更正我的代码以使其生效吗? 谢谢,我在下面添加了我的代码:

var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")

    uilpgr.minimumPressDuration = 2.0

    Map.addGestureRecognizer(uilpgr)

}

func action(gestureRecognizer:UIGestureRecognizer) {

    if gestureRecognizer.state == UIGestureRecognizerState.Began {

        var touchPoint = gestureRecognizer.locationInView(self.Map)

        var newCoordinate = self.Map.convertPoint(touchPoint, toCoordinateFromView: self.Map)

        var location = CLLocation(latitude: newCoordinate.latitude , longitude: newCoordinate.longitude)

这是我正在使用的用户位置代码:

 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        var userLocation:CLLocation = locations[0] as! CLLocation

        var latitude = userLocation.coordinate.latitude
        var longitude = userLocation.coordinate.longitude

        var coordinate = CLLocationCoordinate2DMake(latitude, longitude)

        var latDelta:CLLocationDegrees = 0.01
        var lonDelta:CLLocationDegrees = 0.01

        var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)

        var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)

        self.Map.setRegion(region, animated: true)


    }

触发长按时,只需在地图上添加一个注释对象,该对象是轻量级的模型对象,对应于您的图钉将保存的数据。

let annotation = MKAnnotation();
annotation.title = "My location";
annotation.coordinate = self.Map.userLocation.location.coordinate;
self.Map.addAnnotation(annotation);

添加注释后,请确保您已注册到地图视图的委托,并且它将要求您为添加的注释提供视图。

func mapView(_ mapView: MKMapView!,
    viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
    if(annotation is MKUserLocation){
         return nil;
    }
    let pinView = mapView.dequeueReusableAnnotationForIdentifier("MyIdentifier");
    let pinAnnotationView = MKPinAnnotationView(annotation,reuseIdentifier:"MyIdentifier");
   return pinAnnotationView;
}

我敢肯定有一些语法问题,但希望您理解逻辑。 为用户的位置创建注释。 这将触发您的地图视图的协议方法,并在其中提供带有附加注释的引脚注释视图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM