如何将自定义图钉添加到iPhone MapKit? [英] How do I add custom pins to the iPhone MapKit?

查看:88
本文介绍了如何将自定义图钉添加到iPhone MapKit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试iPhone上的MapKit框架,真的很想将显示位置的标准图钉切换为名为"location.png"的图像.

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?

主控制器

- (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

谢谢!

推荐答案

在查看这是我的解决方案:

- (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;
}

这篇关于如何将自定义图钉添加到iPhone MapKit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆