Obtaining MKAnnotation's coordinate while dragging

人盡茶涼 提交于 2019-12-22 09:39:02

问题


I'm creating a path (MKPolyline) based on the position of annotations added by the user. I want to allow the users to change the path by dragging the pins. I currently can do that, but the MKPolyline doesn't update until the pin is dropped.

I implemented - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState for the MKAnnotationViewDragStateDragging but it only alerts me that the user is dragging the pin and not notifing about the new position.

How can I obtain the current position of the annotation being dragg, every time it changes? I want to be notified about any change in position while dragging to be able to update the MKPolyline to follow the pin as it moves, to better reflect how the path is changing.

Any ideas? Thanks!


回答1:


Create a subclass of MKAnnotationView and use that subclass for the annotation you are dragging. Within that subclass:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CLLocationCoordinate2D location = [_mapView convertPoint:self.center toCoordinateFromView:self.superview];
}

Unfortunately, the MKAnnotation object associated with the MKAnnotationView does not update its coordinate until the MKAnnotationView is dropped. So you have to use the position of the MKAnnotationView itself, and convert that to a valid coordinate.

This also requires a reference to the MKMapView that the annotation has been added to (_mapView here), which you could pass to the view when it is created.

If you have set the centerOffset property of the annotation view, you will also need to account for that:

CLLocationCoordinate2D location = [_mapView convertPoint:CGPointMake(self.center.x - self.centerOffset.x, self.center.y - self.centerOffset.y) toCoordinateFromView:self.superview];



回答2:


Disclaimer: I'm working in Xamarin.iOS/MonoTouch but this solution might apply the same in Objective-C, as most issues dealt with are the same.

I created the custom annotation view as per Avario's suggestion, but the touchesMoved event was never hit. Instead I overrode the Center property (setCenter) and was able to get the coordinate changes that way.



来源:https://stackoverflow.com/questions/16626641/obtaining-mkannotations-coordinate-while-dragging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!