地図にポリラインを表示するiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
#import <MapKit/MapKit.h>
@interface ViewController () <MKMapViewDelegate>
@property (nonatomic, weak) MKMapView *map;
@property (nonatomic, weak) MKPointAnnotation *start;
@property (nonatomic, weak) MKPointAnnotation *end;
@property BOOL line;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createMap];
}
– (void)createMap
{
MKMapView *mv = [[MKMapView alloc] initWithFrame:self.view.bounds];
mv.delegate = self;
[self.view addSubview:mv];
self.map = mv;
}
– (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if (![overlay isKindOfClass:[MKPolyline class]]) {
return nil;
}
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:(MKPolyline *)overlay];
renderer.lineWidth = 3.0f;
renderer.strokeColor = [UIColor blueColor];
renderer.alpha = 0.5;
return renderer;
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
UIView *v = [self.view hitTest:p withEvent:nil];
if (![v isKindOfClass:[MKPinAnnotationView class]]) {
CLLocationCoordinate2D coordinate = [self.map convertPoint:p toCoordinateFromView:self.view];
if (!self.start) {
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = coordinate;
annotation.title = @”START”;
[self.map addAnnotation:annotation];
self.start = annotation;
} else if (!self.end) {
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = coordinate;
annotation.title = @”END”;
[self.map addAnnotation:annotation];
self.end = annotation;
} else if (!self.line){
CLLocationCoordinate2D coordinates[2] = {self.start.coordinate, self.end.coordinate};
MKGeodesicPolyline *geodesicPolyline = [MKGeodesicPolyline polylineWithCoordinates:coordinates count:2];
[self.map addOverlay:geodesicPolyline];
self.line = YES;
}
}
[super touchesBegan:touches withEvent:event];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
static NSString *reuseId = @”pin”;
MKPinAnnotationView *pav = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (pav == nil)
{
pav = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
pav.canShowCallout = YES;
pav.animatesDrop = YES;
pav.pinColor = MKPinAnnotationColorGreen;
}
else
{
pav.annotation = annotation;
}
return pav;
}
@end