Monday, January 5, 2015

Draw Circle around a point on an MKMapView


This is simple app that have an MKMapView and want to draw a circle of particular radius around the user entered location. An overlay view allows us to overlay various shapes on top of a map to signify an area of interest, a route followed etc. There are various built in overlay views such as circles, polygons and lines which inherit from MKShape, but it is also possible to create your own shape.  We generally use one of the inbuilt MKShape objects and then use the corresponding MKOverlayView as a visual representation of our shape.

Framework : MKMapKit

Inherits from: MKOverlayView

Adding a Circle:

  1. Open Xcode 6.
  2. Create new project.
  3. Select: iOS, Application, Single View Application.
  4. Give the project a proper name. In the example, I’ve used the following:
    • Product Name: MapCircleDemo
    • Organization Name: XXXX
    • Class Prefix: XXX
  5. To keep stuff simple, I’ve selected iPad as target device.
    • Click Next.
  6. Now in project navigator you will find “Main.Storyboard”.
  7. Drag and drop MKMapview and add MapKit framework.
  8. Just Control-drag your map to the ViewController.h file and create an IBOutlet. Let’s name our outlet mapView.
  9. Import <MapKit/MapKit.h> in your header file
  10. We now need to return the MKCircleView to display our MKCircle.  We do this using the delegate method mapView:viewForOverlay:  , Add below code

    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
        if ([overlay isKindOfClass:[MKCircle class]]) {
            MKCircleView *circleView = [[MKCircleView alloc] initWithCircle:(MKCircle*)overlay];
            circleView.fillColor = [[UIColor greenColor] colorWithAlphaComponent:0.2];
            circleView.strokeColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
            circleView.lineWidth = 2;
            return circleView;

  11. Design two textfield and get location and radius to draw the circle.
  12. Get location from google places API and get latitude and longitude.
  13. Pass latitude and longitude and radius of circle , Add below code in viewDidLoad.

    int meter = 25*1000;
    MKCircle *circle= [[MKCircle alloc]init];
     circle = [MKCircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(35.26944, -80.84333) radius:meter];
     [self.iMapView addOverlay:circle];

Bharathimohan K is a Software Engineer at Span Technology Services

No comments:

Post a Comment