1

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.

Falko
  • 17,076
  • 13
  • 60
  • 105
anoop
  • 481
  • 4
  • 7

1 Answers1

2

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..

iphonic
  • 12,615
  • 7
  • 60
  • 107
  • First of all thanks for your reply,My idea is when ever user touches the map view a small uiview appear at tap points.By connecting this view coordinates i want to draw polygon overlay.also i can move any of the added view,then overlay also changes corresponding to new coordinates,upto this working fine.But the problem is when ever i zoom or scroll the mapview overlay is changes corresponding to mapview,but the added subview remains in same place.i need to that view in polygon coordinates position. – anoop Apr 26 '13 at 06:19