Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overlay a circle on an iOS map

I've got a radius and a location.

This is how I'm trying to get the bounding rectangle of the circle.

- (MKMapRect)boundingMapRect{

    CLLocationCoordinate2D tmp;
    MKCoordinateSpan radiusSpan = MKCoordinateRegionMakeWithDistance(self.coordinate, 0, self.radius).span;
    tmp.latitude = self.coordinate.latitude - radiusSpan.longitudeDelta;
    tmp.longitude = self.coordinate.longitude - radiusSpanSpan.longitudeDelta;

    MKMapPoint upperLeft = MKMapPointForCoordinate(tmp);
    MKMapRect bounds = MKMapRectMake(upperLeft.x, upperLeft.y, self.radius * 2, self.radius * 2);

    return bounds;
}

MKMapRectMake(...) seems to want width and height measured in Map points. How do I convert the radius to that?

In the end I'm rendering it like this:

MKMapRect theMapRect = [self.overlay boundingMapRect];
CGRect theRect = [self rectForMapRect:theMapRect];
CGContextAddEllipseInRect(ctx, theRect);
CGContextFillPath(ctx);

The radius doesn't seem to equal meters on the map in the end and also the distance doesn't seem to be measured correctly. How to do it right?

I would be really thankful for every hint.

like image 811
kadrian Avatar asked May 07 '13 21:05

kadrian


2 Answers

You should be using MKCircle instead. Do something like:

CLLocationDistance fenceDistance = 300;
CLLocationCoordinate2D circleMiddlePoint = CLLocationCoordinate2DMake(yourLocation.latitude, yourLocation.longitude);
MKCircle *circle = [MKCircle circleWithCenterCoordinate:circleMiddlePoint radius:fenceDistance];
[yourMapView addOverlay: circle];

And adopt the MKMapViewDelegate Method below and do something like this:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay

{
     MKCircleView *circleView = [[[MKCircleView alloc] initWithCircle:(MKCircle *)overlay] autorelease];
     circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.9];
     return circleView;
 }
like image 52
Tommy Devoy Avatar answered Sep 18 '22 15:09

Tommy Devoy


For iOS7 :

Same as tdevoy in viewDidLoad :

CLLocationDistance fenceDistance = 300;
CLLocationCoordinate2D circleMiddlePoint = CLLocationCoordinate2DMake(yourLocation.latitude, yourLocation.longitude);
MKCircle *circle = [MKCircle circleWithCenterCoordinate:circleMiddlePoint radius:fenceDistance];
[yourMapView addOverlay: circle];

But the delegate method (because mapView:viewForOverlay: is deprecated) :

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
    MKCircleRenderer *circleR = [[MKCircleRenderer alloc] initWithCircle:(MKCircle *)overlay];
    circleR.fillColor = [UIColor greenColor];

    return circleR;
}
like image 41
Jon - LBAB Avatar answered Sep 20 '22 15:09

Jon - LBAB