我正在开发我的第一个应用程序并且在其中我只是尝试按下按钮单击显示带有图钉的地图(以及此位置的标题)。我能够加载mapview并让它显示我想要的坐标。但是当我试图显示引脚和注释时,我遇到了问题。不知道在哪里编码以及如何使注释显示引脚。我搜索并看过很多教程,但是大多数都显示了不同的mapview样式,并且在用户选择上显示引脚,我想在地图加载时显示引脚。
以下是我必须显示正在运行但没有引脚显示或注释的地图的代码:
FirstLocateViewController.m代码:
#import "FirstLocateViewController.h"
@implementation FirstLocateViewController
@synthesize dismissViewButton;
-(IBAction)dismissView:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = CGRectMake(0,0, 320,420);
mapView = [[MKMapView alloc] initWithFrame:frame];
mapView.mapType = MKMapTypeStandard;
CLLocationCoordinate2D coord = {latitude: 12.3456, longitude: -7.890};
MKCoordinateSpan span = {latitudeDelta: 0.05, longitudeDelta: 0.05};
MKCoordinateRegion region = {coord, span};
[mapView setRegion:region];
[self.view addSubview:mapView];
}
FirstLocateViewController.h代码:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
@interface FirstLocateViewController : UIViewController <MKMapViewDelegate> {
UIButton *dismissViewButton;
MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet UIButton *dismissViewButton;
- (IBAction)dismissViewButton:(id)sender;
@end
感谢您提前获得任何重要帮助。
答案 0 :(得分:14)
为此你需要创建一个注释创建一个具有CLLocationCoordinate2D,title,subtitle这样的类 .h文件
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
@interface DisplayMap : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end
和.m文件
#import "DisplayMap.h"
@implementation DisplayMap
@synthesize coordinate,title,subtitle;
-(void)dealloc{
[title release];
[super dealloc];
}
@end
然后将以下代码添加到viewdidload
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title=@"put title here";
ann.coordinate = region.center;
[mapView addAnnotation:ann];
并实施以下方法
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = @"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorPurple;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
}
else {
[mapView.userLocation setTitle:@"I am here"];
}
return pinView;
}
遵循此tutorial:代码并给出解释:
答案 1 :(得分:1)
您需要创建一个“地图注释”对象 - 实际上可以是任何对象,但它必须符合MKAnnotation协议(因此您基本上可以将对象声明为
@interface MyAnnotation: NSObject<MKAnnotation>
)。在手册中查看该协议,它只是3个方法和一个属性(坐标)。设置坐标和标题,然后将注释添加到mapView([self.mapView addAnnotation:annotation])