iOS4 Map Kit – Custom Map Overlay Tool – MKPolyline

1

Category : Development, iPhone

Simple MKPolyLine overlay.

In my previous post I spoke about iOS4′s MapKit additions. One was the ability to easily add draggable annotation views to your maps. The other, and the one I will be covering here, is the ability to add custom overlays to your maps.

Map overlays are very useful when trying to highlight specific areas to yours users. In this example I have used to MKPolyLine overlay view.

In this project I add annotations to the map then drag them into the place I would like. Each time I add a new annotation I connect the annotations when an MKPolyLine overlay. I do this by adding an IBAction to the “+” BarButtonItem then call a selector addPin:.

 - (IBAction)addPin:(id)sender {
   CurrentLocationAnnotation *annotation = [[[CurrentLocationAnnotation alloc] initWithCoordinate:self.currentLocation.coordinate addressDictionary:nil] autorelease];
      annotation.title = [[NSString alloc] initWithFormat:@"%d", [mvMapView.annotations count] + 1];
      annotation.subtitle = @"Drag pin to set poisition.";
   [mvMapView addAnnotation:annotation];
   [annotation release];
 }

I wait until the user drags the pin into its proper place before calling the connectDots method to draw the actual poly lines. The MKPolyLine needs an array of coordinates to draw to and from and the number of coordinates in the array.

 - (void)connectDots {
   NSInteger arrayCount = [mvMapView.annotations count];
   CLLocationCoordinate2D coords[arrayCount];
   NSInteger i;
   for (i=0;i<arrayCount;i++) {
     MKPlacemark *placeMark = [mvMapView.annotations objectAtIndex:i];
     coords[i] = placeMark.coordinate;
     NSLog(@"%d, %d", coords[i].latitude, coords[i].longitude);
   }
   MKPolyline *polyLine=[MKPolyline polylineWithCoordinates:coords count:[mvMapView.annotations count]];
   [mvMapView addOverlay:polyLine];
   [polyLine release];
 }

When you call addOverlay on the map view, it looks for the delegate method viewForOverlay. This is where you can set the specific details of the poly line view.

 -(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay{
   MKPolylineView *polyLineView = [[[MKPolylineView alloc] initWithOverlay:overlay] autorelease];
   polyLineView.strokeColor = [UIColor redColor];
   polyLineView.lineWidth = 5.0;
   return polyLineView;
 }

I built this tool to help you easily mark out your coordinates for your custom overlay. Hope it helps! Let me know if you have any questions. Happy Coding!

Source: OverlayMapper

Comments (1)

Post a comment