adding multiple circles around a pin in iOS

2019-08-06 13:32发布

问题:

How can I add and display multiple circles in different colors inside a map (MKMapView)? I figured out how to add one circle, but can't figure out how to add multiple circles in various sizes and colors ... any help would be appreciated!

回答1:

Here's some code I use to draw two concentric circles at a given location on the map. The outer one is gray, and the inner one is white. (in my example "range" is the circle radius) Both have some transparency:

- (void)drawRangeRings: (CLLocationCoordinate2D) where {
    // first, I clear out any previous overlays:
    [mapView removeOverlays: [mapView overlays]];
    float range = [self.rangeCalc currentRange] / MILES_PER_METER;
    MKCircle* outerCircle = [MKCircle circleWithCenterCoordinate: where radius: range];
    outerCircle.title = @"Stretch Range";
    MKCircle* innerCircle = [MKCircle circleWithCenterCoordinate: where radius: (range / 1.425f)];
    innerCircle.title = @"Safe Range";

    [mapView addOverlay: outerCircle];
    [mapView addOverlay: innerCircle];
}

Then, make sure your class implements the MKMapViewDelegate protocol, and define how your overlays look in the following method:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MKCircle* circle = overlay;
    MKCircleView* circleView = [[MKCircleView alloc] initWithCircle: circle];
    if ([circle.title compare: @"Safe Range"] == NSOrderedSame) {
        circleView.fillColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.25];
        circleView.strokeColor = [UIColor whiteColor];
    } else {
        circleView.fillColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.25];
        circleView.strokeColor = [UIColor grayColor];
    }
    circleView.lineWidth = 2.0;

    return circleView;
}

And, of course, don't forget to set the delegate on your MKMapView object, or the above method will never get called:

mapView.delegate = self;