Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

objective c - How do I add custom pins to the iPhone MapKit?

I'm testing out the MapKit framework on the iPhone and would really much like to switch the standard pin that displays a location to an image called "location.png".

How can I modify my code to allow that?

Maincontroller

- (void)viewDidLoad
{
    [super viewDidLoad];

    //
    // Set the map center
    //
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = 49.2802;
    coordinate.longitude = -123.1182;
    mapView.region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000);

    //
    // Set 10 random locations on the map for testing purposes
    //
    for(int i = 0; i < 10; i++)
    {
        CGFloat latDelta = rand()*.035/RAND_MAX -.02;
        CGFloat longDelta = rand()*.03/RAND_MAX -.015;

        CLLocationCoordinate2D newCoord = { coordinate.latitude + latDelta, coordinate.longitude + longDelta };
        MapAnnotation* annotation = [[MapAnnotation alloc] initWithCoordinate:newCoord];
        [mapView addAnnotation:annotation];
        [annotation release];
    }

    [mapView setDelegate:self];
}

MapAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MapAnnotation : NSObject <MKAnnotation> {
    CLLocationCoordinate2D _coordinate;
}

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;

@end

MapAnnotation.m

#import "MapAnnotation.h"

@implementation MapAnnotation
@synthesize coordinate = _coordinate;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    self = [super init];

    if (self != nil)
    {
        _coordinate = coordinate;
    }

    return self;
}

@end

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved it after looking at the source for MapCallouts

Here is my solution:

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *AnnotationViewID = @"annotationViewID";

    MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];

    if (annotationView == nil)
    {
        annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
    }

    annotationView.image = [UIImage imageNamed:@"location.png"];
    annotationView.annotation = annotation;

    return annotationView;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...