iPhone/iPad – Adding overlay


This blog is about adding custom overlay to a map. Overlays like polygon and circle can be added to the map. For instance you want to highlight or outline an area of a state or states in a country. In my application i have outlined all the states in US.

MKMapKit provides MKPolygon class and add overlay to achieve this. This can be done with easy four steps
1. Initialize map
2. Get coordinates
3. Create Polygon and add to map.
4. Implement delegate
1. Initialize Map :
Initialize the map view and add it as subview.

MKMapView _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 28, 360, 250)];

MKCoordinateRegion region;

region.center.latitude = 42.5116;

region.center.longitude = -90.6290;

region.span.longitudeDelta = 26.0;

region.span.latitudeDelta = 26.0;

_mapView.showsUserLocation = NO;

[_mapView setScrollEnabled:YES];

[_mapView setRegion:region];

[_mapView setDelegate:self];

[self.view addSubview:_mapView];

2. Get Coordinates
Here in this example, i have outlined all the US states. So to draw a polygon we need coordinates of all the state. Coordinates can be saved in local file or local database. This is the link to get coordinates of all US state
3. CreatePolygon:
Below is the code to add polygon

NSMutableArray* points; (contains coordinates of particular state)

CLLocationCoordinate2D *coords =

malloc(sizeof(CLLocationCoordinate2D) * [points count]);

 

for(int idx = 0; idx < [points count]; idx++) {

CLLocation* location = [points objectAtIndex:idx];

coords[idx] = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

}

polygon = [MKPolygon polygonWithCoordinates:coords count:[points count]];

free(coords);

[_mapView addOverlay:polygon];

 

3. Implement Delegate

 

 

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay

{

MKPolygonView *polygonView = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease];

polygonView.lineWidth = 0.5;

polygonView.strokeColor = [UIColor whitecolor];

polygonView.fillColor = [[UIColor colorWithRed:0.9176 green:0.9098 blue:0.8117 alpha:1.0] colorWithAlphaComponent:0.5];;

return polygonView;

}

 

zooming also taken care by this implementation. We dont need to do extra coding to handle zoom.
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s