Create overlay from user interaction on MKMapView?
I have two questions,
How to create an overlay on a 开发者_开发百科MKMapkitView from user's touch down events? i.e. To keep it simple, the user touches down and it creates a MKCircle overlay
How does the Maps application implements the "dropped pin" on touch down? Anybody knows or have some code examples on how to accomplish something similar?
Any pointers would be greatly appreciated. I've been googling and reading lots of docs without much success as you can see.
Below is an example that creates a circle and drops a pin where the user touches and holds their finger for 1 second. It uses a UILongPressGestureRecognizer which is added to the mapView wherever the map is initialized (eg. viewDidLoad).
Make sure the mapView's delegate is set also.
// In viewDidLoad or where map is initialized...
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0; //user must hold for 1 second
[mapView addGestureRecognizer:lpgr];
[lpgr release];
...
- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
CLLocationCoordinate2D touchMapCoordinate = [mapView convertPoint:touchPoint toCoordinateFromView:mapView];
//add pin where user touched down...
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = touchMapCoordinate;
pa.title = @"Hello";
[mapView addAnnotation:pa];
[pa release];
//add circle with 5km radius where user touched down...
MKCircle *circle = [MKCircle circleWithCenterCoordinate:touchMapCoordinate radius:5000];
[mapView addOverlay:circle];
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay
{
MKCircleView* circleView = [[[MKCircleView alloc] initWithOverlay:overlay] autorelease];
circleView.fillColor = [UIColor redColor];
return circleView;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *AnnotationIdentifier = @"Annotation";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (!pinView)
{
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.animatesDrop = YES;
}
else
{
pinView.annotation = annotation;
}
return pinView;
}
精彩评论