3

I've a MKPolyline made of CLLocationCoordinate2D array (Points). That's all fine.

I added this line to the Map as an overlay, like so: Map.AddOverlay(line);

I event set this: Map.SetVisibleMapRect(line.BoundingMapRect, true);

But the line does not show up although the Map bounds are correct.

I'm looking into MKPolylineView, but can't get it to work.

Anyone knows to set colour and line width?

Thanks

Julien Pierre
  • 467
  • 1
  • 6
  • 29
  • I haven't used MonoTouch but did you implement the viewForOverlay delegate method? Is the map view's delegate property set? Are you able to add regular annotations to the map? –  May 29 '11 at 17:04
  • Yes I am able to add regular annotations. I tried implementing the viewForOverlay delegate, but does not work. Do you have an example of viewForOverlay in Objective-C? – Julien Pierre May 29 '11 at 17:21
  • See http://stackoverflow.com/questions/5474299/iphone-mkmapview-mkpolygon-issues/5474737#5474737. Also try the Apple sample apps [Breadcrumb](http://developer.apple.com/library/ios/ipad/#samplecode/Breadcrumb/Introduction/Intro.html) and KMLViewer (though this one is a bit over complicated). –  May 29 '11 at 17:36
  • I can't get my head around this viewForOverlay. In Monotouch it's a method in which I need to pass a NSObject overlay. I don't quite understand how to use it. – Julien Pierre May 29 '11 at 17:57
  • The viewForOverlay method will be called automatically by the map view--not by your code. It might help if you show the code that creates the `line` object before you call `AddOverlay`. –  May 29 '11 at 18:44

2 Answers2

8

After much head scratching, here is how to display a MKPolyline on a MKMapView:

Step 1: Create a delegate method for Map GetViewForOverlay

Map.GetViewForOverlay = Map_GetViewForOverlay;

Where Map is the MKMapView.

MKOverlayView Map_GetViewForOverlay(MKMapView mapView, NSObject overlay)
{
    if(overlay.GetType() == typeof(MKPolyline))
    {
       MKPolylineView p = new MKPolylineView((MKPolyline)overlay);
       p.LineWidth = 2.0f;
       p.StrokeColor = UIColor.Green;
       return p;
    }
    else
        return null;
}

Step 2: Create a new instance of MKPolyline

MKPolyline line = MKPolyline.FromCoordinates(polyPoints);

Where polyPoints is an Array of CLLocationCoordinate2D.

Step 3: Add the overlay to the map

Map.AddOverlay(line);

Step 4: Use code below to zoom and change Map bounds to fit route

Map.SetVisibleMapRect(line.BoundingMapRect, true);
Julien Pierre
  • 467
  • 1
  • 6
  • 29
1

I'm pretty sure if your intent is to dynamically draw a map over the MapView given a backing model object that indicates two coordinates you want to take a look at my project here:

https://github.com/anujb/MapWithRoutes

This will allow you to overlay a path and it will update as the map changes. It's a modified version of an obj-C port that makes use of background threads so it's not blocking.

Thanks,

Anuj

Anuj
  • 3,134
  • 13
  • 17