How to overlay a circle on an iOS map

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 03:49:22

问题


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.


回答1:


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;
 }



回答2:


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;
}


来源:https://stackoverflow.com/questions/16428918/how-to-overlay-a-circle-on-an-ios-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!