準備任務(wù):
infoplist? 文件中配置:Localization native development region
viewcontroller .m:
#import "ViewController.h"#import#import "HMAnnotation.h"
#import "HMAnnotationView.h"
#import "HMAnnotation.h"
#import <MapKit/MapKit.h>
//在loadview方法中定義mapview
- (void)loadView {
MKMapView *mapView = [[MKMapView alloc] init];
self.view = mapView;
self.mapView = mapView;
mapView.delegate = self;
}
自定義的大頭針逸寓,保證大頭針扎在地圖上
贬派!
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{
//? 獲取當(dāng)前的觸摸對象
UITouch *touch = [touches anyObject];
//? 用戶觸摸的點
CGPoint location = [touch locationInView:self.view];
//? 讓大頭針在底部在觸摸點上
UIImage *image = [UIImage imageNamed:@"category_1"];
location.y = location.y - image.size.height * 0.5;
//? 把View上坐標的點查蓉,轉(zhuǎn)換為地圖經(jīng)緯度
CLLocationCoordinate2D coordinate? = [self.mapView convertPoint:location toCoordinateFromView:self.view];
//? 添加大頭針(標注)
HMAnnotation *annotation = [[HMAnnotation alloc] init];
annotation.coordinate = coordinate;
annotation.title = @"黑馬程序員";
annotation.subtitle = @"IT教育領(lǐng)導(dǎo)者";
//? 設(shè)置一個0-4的隨機數(shù)
annotation.type = arc4random_uniform(5);
//? 添加大頭針模型到地圖上
[self.mapView addAnnotation:annotation];
}
// 返回一個可以重用的大頭針
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation
{
if ([annotation isKindOfClass:[HMAnnotation class]]) {
NSString *reuseID = @"hmAnnotationView";
HMAnnotationView *annotationView = (HMAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseID];
if (annotationView == nil) {
annotationView = [[HMAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseID];
annotationView.canShowCallout = YES;
}
annotationView.annotation = annotation;
return annotationView;
}
return nil;
}
/**
只有當(dāng)大頭針被添加到了,地圖上之后椎椰,才能執(zhí)行動畫
*/
/**
當(dāng)大頭針已經(jīng)被添加到了地圖執(zhí)行
@param views? 大頭針數(shù)組
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray*)views
{
for (MKAnnotationView *annotationView in views) {
//? ? ? 1. 記錄當(dāng)前大頭針的位置
CGPoint center? = annotationView.center;
//? ? ? 2. 使用不帶動畫的方式哺呜,把大頭針視圖移動地圖的頂部
annotationView.center = CGPointMake(center.x, 0);
//? ? ? 3. 使用動畫讓大頭針視圖回到原來的位置
[UIView animateWithDuration:0.2 animations:^{
annotationView.center = center;
}];
}
}