iosios7mkmapviewmkoverlaymkpolygon

Create Square Overlay that covers current region in MKMapView


How can I create a Square Overlay that will cover the current region of my MKMapView. My MKMapView is set with coordinates of the users current location but they are centre coordinates. How do I calculate the square coordinates so I can create a square overlay that fits perfectly in the current view?

Thanks guys!


Solution

  • You can use the centerCoordinate and region properties of MKMapView and then create a MKPolygon overlay by extracting the four corners, as in the code below:

        vertex[0]=CLLocationCoordinate2DMake(map.centerCoordinate.latitude+map.region.span.latitudeDelta/2.,map.centerCoordinate.longitude-map.region.span.longitudeDelta/2.);
        vertex[1]=CLLocationCoordinate2DMake(map.centerCoordinate.latitude+map.region.span.latitudeDelta/2.,map.centerCoordinate.longitude+map.region.span.longitudeDelta/2.);
        vertex[2]=CLLocationCoordinate2DMake(map.centerCoordinate.latitude-map.region.span.latitudeDelta/2.,map.centerCoordinate.longitude+map.region.span.longitudeDelta/2.);
        vertex[3]=CLLocationCoordinate2DMake(map.centerCoordinate.latitude-map.region.span.latitudeDelta/2.,map.centerCoordinate.longitude-map.region.span.longitudeDelta/2.);
        MKPolygon *square = [MKPolygon polygonWithCoordinates:vertex count:4];
    

    Then you add the polygon as an overlay:

    [map addOverlay:square]

    Finally in your mapView:rendererForOverlay: you define your square rendered based on the polygon overlay:

    - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id)overlay {  
        if([overlay isKindOfClass:[MKPolygon class]]) {
            MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:(MKPolygon *)overlay];
            renderer.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.25];
            return renderer;
        } else {
            return nil;
        }    
    }