生活随笔
收集整理的這篇文章主要介紹了
地图与定位之大头针视图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
該博文在上一博文地圖與定位之地圖、大頭針的基礎上完成。
在MyAnnotation.h 中增加屬性
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
//MKAnnotation是一個協議 ,添加大頭針久需要實現該協議
//coordinate 屬性是必須的,所以需要實現該屬性
@interface MyAnnotation : NSObject<MKAnnotation>
@property(nonatomic,strong)UIImage *image;
-(id)initWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title subtitle:(NSString *)subtitle;
@end
?在ViewController.m中
//
// ViewController.m
// MapView
//
// Created by City--Online on 15/4/17.
// Copyright (c) 2015年 CYW. All rights reserved.
//#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "MyAnnotation.h"
@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
@property(nonatomic,strong)MKMapView *mapView;
@property(nonatomic,strong)CLLocationManager *locationManager;
@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];_locationManager=[[CLLocationManager alloc]init];BOOL enable=[CLLocationManager locationServicesEnabled];NSLog(@"%d",[CLLocationManager authorizationStatus]);if (!enable) {NSLog(@"用戶未開啟定位服務,無法定位");return;}else if ([CLLocationManager authorizationStatus]<3){[_locationManager requestWhenInUseAuthorization];}CLLocationDistance distance=10.0;_locationManager.distanceFilter=distance;_locationManager.delegate=self;_locationManager.desiredAccuracy=kCLLocationAccuracyBest;[_locationManager startUpdatingLocation];self.mapView=[[MKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];//地圖類型
// typedef NS_ENUM(NSUInteger, MKMapType) {
// MKMapTypeStandard = 0, //標準地圖
// MKMapTypeSatellite, //衛星地圖
// MKMapTypeHybrid //混合地圖
// }self.mapView.mapType=MKMapTypeStandard;//是否定位當前位置 否顯示當前位置self.mapView.showsUserLocation=YES;//代理設置self.mapView.delegate=self;// typedef struct {
// CLLocationCoordinate2D center;
// MKCoordinateSpan span;
// } MKCoordinateRegion;//中心點經緯度CLLocationCoordinate2D locationCoordinate2D;locationCoordinate2D.latitude=22.544349;locationCoordinate2D.longitude= 113.94787;//范圍比例尺MKCoordinateSpan coordinateSpan;//緯度coordinateSpan.latitudeDelta=0.05;//經度coordinateSpan.longitudeDelta=0.05;//設置顯示區域MKCoordinateRegion coordinateRegion;coordinateRegion.center=locationCoordinate2D;coordinateRegion.span=coordinateSpan;[self.mapView setRegion:coordinateRegion animated:YES];
// self.mapView.region=coordinateRegion;// typedef NS_ENUM(NSInteger, MKUserTrackingMode) {
// MKUserTrackingModeNone = 0, // the user's location is not followed
// MKUserTrackingModeFollow, // the map follows the user's location
// MKUserTrackingModeFollowWithHeading, // the map follows the user's location and heading
// }self.mapView.userTrackingMode=MKUserTrackingModeFollow;[self.view addSubview:self.mapView];UISegmentedControl *segmentedControl=[[UISegmentedControl alloc]initWithItems:@[@"普通地圖",@"衛星地圖",@"混合地圖"]];segmentedControl.selectedSegmentIndex=0;[segmentedControl addTarget:self action:@selector(selectSegmentIndex:) forControlEvents:UIControlEventValueChanged];self.navigationItem.titleView=segmentedControl;//定義大頭針類MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:locationCoordinate2D title:@"主標題" subtitle:@"子標題"];annotation.image=[UIImage imageNamed:@"map.png"];[self.mapView addAnnotation:annotation];//定義長按手勢UILongPressGestureRecognizer *longPressGestureRecognizer=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(LongTap:)];[self.mapView addGestureRecognizer:longPressGestureRecognizer];}
-(void)LongTap:(UILongPressGestureRecognizer *)gestureRecongizer
{if (gestureRecongizer.state==UIGestureRecognizerStateBegan) {NSLog(@"開始長按");//獲取mapview手指點擊位置CGPoint point=[gestureRecongizer locationInView:self.mapView];//轉化為經緯度CLLocationCoordinate2D coordinate2D=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];//把當前位置轉為地理位置CLGeocoder *geocoder=[[CLGeocoder alloc]init];CLLocation *location=[[CLLocation alloc]initWithLatitude:coordinate2D.latitude longitude:coordinate2D.longitude];[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {if (error) {NSLog(@"失敗:%@",error);return ;}if (placemarks.count>0) {CLPlacemark *placemark=[placemarks firstObject];MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:coordinate2D title:placemark.name subtitle:placemark.thoroughfare];annotation.image=[UIImage imageNamed:@"map.png"];NSLog(@"城市:%@",placemark.locality);NSLog(@"區:%@",placemark.subLocality);NSLog(@"省份:%@",placemark.administrativeArea);[self.mapView addAnnotation:annotation];}}];}else if(gestureRecongizer.state==UIGestureRecognizerStateChanged){NSLog(@"長按移動");}else if(gestureRecongizer.state==UIGestureRecognizerStateEnded){NSLog(@"長按結束");}}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{if (locations.count>0) {CLLocation *location=[locations firstObject];CLLocationCoordinate2D locationCoordinate2D =location.coordinate;[self.mapView setRegion:MKCoordinateRegionMake(locationCoordinate2D, self.mapView.region.span) animated:YES];NSLog(@"%lf ,%lf",locationCoordinate2D.longitude,locationCoordinate2D.longitude);MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:locationCoordinate2D title:@"定位位置" subtitle:@"子標題"];annotation.image=[UIImage imageNamed:@"map.png"];[self.mapView addAnnotation:annotation];}
}-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{//由于當前位置的標注也是一個大頭針,所以此時需要判斷,此代理方法返回nil使用默認大頭針視圖if ([annotation isKindOfClass:[MyAnnotation class]]) {static NSString *key=@"annotation";MKAnnotationView *annotationView=[self.mapView dequeueReusableAnnotationViewWithIdentifier:key];if (annotationView==nil) {annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key];//允許交互點擊annotationView.canShowCallout=true;//定義詳情視圖偏移量annotationView.calloutOffset=CGPointMake(0, 1);//詳情左視圖UIImageView *imgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"email.png"]];imgView.frame=CGRectMake(20, 20, 40, 40);annotationView.leftCalloutAccessoryView=imgView;UIButton *btn=[UIButton buttonWithType:UIButtonTypeInfoDark];btn.frame=CGRectMake(20, 20, 40, 40);annotationView.rightCalloutAccessoryView=btn;}//修改大頭針視圖//重新設置此類大頭針視圖的大頭針模型(因為有可能是從緩存池中取出來的,位置是放到緩存池時的位置)annotationView.annotation=annotation;
// //設置大頭針圖片annotationView.image=((MyAnnotation *)annotation).image;return annotationView;}else{return nil;}
}//大頭針選中
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{MyAnnotation *annotation=view.annotation;NSLog(@"%@",annotation.title);
}
//定位失敗
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{NSLog(@"定位失敗");NSLog(@"%@",error);
}
- (void)selectSegmentIndex:(UISegmentedControl *)control
{NSInteger index = control.selectedSegmentIndex;/*MKMapTypeStandard 普通地圖(標準地圖),MKMapTypeSatellite 衛星地圖,MKMapTypeHybrid 混合地圖*/MKMapType mapType;switch (index){//普通地圖case 0:mapType = MKMapTypeStandard;break;//衛星地圖case 1:mapType = MKMapTypeSatellite;break;//普通和衛星的混合地圖case 2:mapType = MKMapTypeHybrid;break;default:break;}//改變地圖類型self.mapView.mapType = mapType;
}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}@end
?
總結
以上是生活随笔為你收集整理的地图与定位之大头针视图的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。