iOS SDK: MapKit MKPolyLine not showing

╄→гoц情女王★ 提交于 2019-12-04 16:47:44

There are two issues with the code shown:

  1. The polyline is being created using MKMapPoints which are incorrectly set to latitude/longitude values. An MKMapPoint is not degrees of latitude/longitude. It is an x/y transformation of a lat/long on the flat map projection. Either convert the latitude/longitude values to MKMapPoints using MKMapPointForCoordinate or just use CLLocationCoordinate2D instead. Just using CLLocationCoordinate2D when you have the lat/long is much easier to code and understand.
  2. In viewForOverlay, the code is creating an empty MKOverlayView which is invisible. Create an MKPolylineView instead (a subclass of MKOverlayView that draws MKPolylines) and set its strokeColor.


For the first issue, use:

  • CLLocationCoordinate2D instead of MKMapPoint,
  • CLLocationCoordinate2DMake instead of MKMapPointMake,
  • and polylineWithCoordinates instead of polylineWithPoints


For the second issue, here's an example:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineView *mapOverlayView = [[MKPolylineView alloc] initWithPolyline:overlay];
        //add autorelease if not using ARC
        mapOverlayView.strokeColor = [UIColor redColor];
        mapOverlayView.lineWidth = 2;
        return mapOverlayView;
    }

    return nil;
}


A couple of other things:

  • Instead of valueForKey:@"lat", I would use objectForKey:@"lat" (same for @"lng").
  • Make sure the map view's delegate is set otherwise the viewForOverlay delegate method will not get called even with all the other changes.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!