anoop
anoop

Reputation: 481

Add a subview to MKMapView (not an overlay)

I want to add a small subview at tap point on an iOS map view in such a way that added subview also zooms and scrolls when I scroll and zoom the map view. Any help? The code I have tried is below:

- (void)viewDidLoad
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foundTap:)];
    tapRecognizer.numberOfTapsRequired = 1;
    tapRecognizer.numberOfTouchesRequired = 1;
    [self.myMapView addGestureRecognizer:tapRecognizer];
}

- (IBAction)foundTap:(UITapGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer locationInView:self.myMapView];
    dotimage = [[UIView alloc]initWithFrame:CGRectMake(point.x,point.y , 10, 10)];
    dotimage.backgroundColor = [UIColor redColor];
    [self.myMapView addSubview:dotimage];
}

The view dotimage is not moving and scrolling with the map view.

Upvotes: 1

Views: 1875

Answers (1)

iphonic
iphonic

Reputation: 12719

Your approach is wrong, you cannot get the view added as subview in map zoomed, you have to add a custom pin on tap, the custom pin should look like your view you want to add..

You can try the code below

- (void)viewDidLoad
{
      UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCustomView:)];
      [recognizer setNumberOfTapsRequired:1];
      [map addGestureRecognizer:recognizer];
      [recognizer release];
}

- (void)addCustomView:(UITapGestureRecognizer*)recognizer
{
  CGPoint tappedPoint = [recognizer locationInView:map];
  //Get the coordinate of the map where you tapped
  CLLocationCoordinate2D coord= [map convertPoint:tappedPoint toCoordinateFromView:map];

    //Add Annotation
    /* Create a custom annotation class which takes coordinate  */
    CustomAnnotation *ann=[[CustomAnnotation alloc] initWithCoord:coord];
    [map addAnnotation:ann];

}

Then in you map delegate function

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
   if([annotation isKindOfClass:[CustomAnnotation class]])
    {
       //Do your annotation initializations 

       // Then return a custom image that looks like your view like below
       annotationView.image=[UIImage imageNamed:@"customview.png"]; 
    }
}

All the Best..

Upvotes: 2

Related Questions