Luck Yong
Luck Yong

Reputation: 111

Drawing a MKCircle on a map view

I need to draw a circle to display the distance around a point that I have plotted.

Where should I implement these two lines of code to make it work? I tried putting it in viewWillAppear: but the circle does not appear.

[self addCircle:_coordinate];
[self addCircleWithRadius:5.5 addCircleWithCoordinate:_coordinate];

- (void)addCircle: (CLLocationCoordinate2D)coordinate
{
    // draw the radius circle for the marker

    double radius = 2000.0;
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:coordinate radius:radius];
    [circle setTitle:@"background"];
    [_mapView addOverlay:circle];

    MKCircle *circleLine = [MKCircle circleWithCenterCoordinate:coordinate radius:radius];
    [circleLine setTitle:@"line"];
    [_mapView addOverlay:circleLine];
}

- (void)addCircleWithRadius:(double)radius addCircleWithCoordinate: (CLLocationCoordinate2D) coordinate
{

    MKCircle *circle = [MKCircle circleWithCenterCoordinate:coordinate radius:radius];
    [circle setTitle:@"background"];
    [_mapView addOverlay:circle];

    MKCircle *circleLine = [MKCircle circleWithCenterCoordinate:coordinate radius:radius];
    [circleLine setTitle:@"line"];
    [_mapView addOverlay:circleLine];
}

- (void)sliderChanged:(UISlider*)sender
{
    [_mapView removeOverlays:[_mapView overlays]];

    double radius = (sender.value * 100);
    CLLocationCoordinate2D coordinate = self.coordinate;

    [self addCircleWithRadius:radius addCircleWithCoordinate:coordinate];
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay{
    MKCircle *circle = overlay;
    MKCircleView *circleView = [[[MKCircleView alloc] initWithCircle:overlay] autorelease];

    if ([circle.title isEqualToString:@"background"])
    {
        //circleView.fillColor = UIColorFromRGB(0x598DD3);
        circleView.alpha = 0.25;
    }
    else
    {
        //circleView.strokeColor = UIColorFromRGB(0x5C8AC7);
        circleView.lineWidth = 2.0;
    }

    return circleView;
}

Upvotes: 2

Views: 8026

Answers (1)

Peter DeWeese
Peter DeWeese

Reputation: 18333

While you could try viewDidAppear instead of viewWillAppear, I think it should already work in that regard. I think that you have something else wrong, and you should step through with a debugger to find it. Check the usual suspects:

  • Set the fill color. Make it opaque and obvious.
  • _mapView might be nil or zombied during runtime. (or not mapped in your xib)
  • The coordinates or radius may be different than you expect. Check the actual coordinate values in your debugger.
  • Everything may be correct except that the coordinates are not located in your map's zoomed area.

Upvotes: 1

Related Questions