IOS 使用谷歌地图API在IOS设备上定位到自己(七)

         这两天抽时间学习了一下IOS下谷歌地图的API  现在很多APP中都会使用谷歌的地图。 个人觉得开发起来还是非常的便利的。废话不多说啦,赶快进入今天的正题。如下所示,这个项目我是在iPhone上调试的,这正是我的手机,模拟器上我没有试过,模拟器肯定是能打开谷歌地图的,但是好像不能定位地点。大家仔细看我下面的代码描述,其实很简单 真的很简单。

 

 

OK下面是代码片段。

创建一个工程,如下图所示,先将CoreLocation.framework 和 MapKit.framework  引入工程中,前者是负责定位的,后者是负责地图的。

 

 

AppDelegate.h  入口类,没什么好说的我就不解释了。

 

1 #import <UIKit/UIKit.h>
2 #import "MapViewController.h"
3  
4 @interface AppDelegate : UIResponder <UIApplicationDelegate>
5  
6 @property (strong, nonatomic) UIWindow *window;
7 @property (strong, nonatomic) UINavigationController *navController;
8 @property (strong, nonatomic) UIViewController *viewController;
9 @end

 

AppDelegate.m

01 #import "AppDelegate.h"
02  
03 @implementation AppDelegate
04  
05 @synthesize window = _window;
06 @synthesize navController;
07 @synthesize viewController;
08  
09 - (void)dealloc
10 {
11     [_window release];
12     [super dealloc];
13 }
14  
15 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
16 {
17     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
18  
19     self.window.backgroundColor = [UIColor whiteColor];
20     self.viewController =  [[MapViewController alloc]init];
21     self.navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
22     [self.window addSubview:navController.view];
23  
24     [self.window makeKeyAndVisible];
25     return YES;
26 }
27  
28 @end

 

主要的东东都写在MapViewController中,请大家仔细看这里。

MapViewController.h

01 #import <UIKit/UIKit.h>
02 #import <MapKit/MKReverseGeocoder.h>
03 #import <CoreLocation/CoreLocation.h>
04 #import <MapKit/MapKit.h>
05  
06 @interface MapViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate>
07 {
08  
09    //地图视图, 谷歌地图将加载在这个视图中喔
10    MKMapView *myMapView ;
11    //地图定位管理器
12    CLLocationManager *_locManager ;
13 }
14  
15 @end

 

MapViewController.m 注意看这个类噢。

001 #import "MapViewController.h"
002  
003 @implementation MapViewController
004  
005 - (void)dealloc
006 {
007     [_locManager release];
008     [super dealloc];
009 }
010  
011 - (void)viewDidLoad
012 {
013  
014     [super viewDidLoad];
015  
016      self.navigationItem.title  = @"雨松MOMO"
017  
018     myMapView = [[[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
019     myMapView.delegate = self;
020     //在这里先让地图视图隐藏起来,
021     //等获取当前经纬度完成后在把整个地图显示出来
022     myMapView.hidden = true;
023     [self.view addSubview:myMapView];
024  
025     //创建定位管理器,
026     _locManager = [[CLLocationManager alloc] init];
027     [_locManager setDelegate:self];
028     [_locManager setDesiredAccuracy:kCLLocationAccuracyBest];  
029  
030 }
031  
032 -(void) viewWillAppear:(BOOL)animated
033 {
034  
035     [super viewWillAppear:animated];
036  
037     //开始使用手机定位,这是一个回调方法,
038     //一旦定位完成后程序将进入
039     //- (void)locationManager:(CLLocationManager *)manager
040     //didUpdateToLocation:(CLLocation *)newLocation
041     //fromLocation:(CLLocation *)oldLocation
042     //方法中
043  
044     [_locManager startUpdatingLocation];
045  
046 }
047  
048 //定位成功后将进入此方法
049 - (void)locationManager:(CLLocationManager *)manager
050     didUpdateToLocation:(CLLocation *)newLocation
051            fromLocation:(CLLocation *)oldLocation
052 {
053  
054     //得到当前定位后的经纬度,当前经纬度是有一定偏移量的,
055     //使用另一种方法可以很好的解决这个问题
056     CLLocationCoordinate2D loc = [newLocation coordinate];
057     float lat =  loc.latitude;
058     float lon = loc.longitude;
059  
060     //让MapView使用定位功能。
061     myMapView.showsUserLocation =YES;
062  
063     //更新地址,
064     [manager stopUpdatingLocation];
065  
066     //设置定位后的自定义图标。
067     MKCircle* circle = [MKCircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(myMapView.userLocation.location.coordinate.latitude, myMapView.userLocation.location.coordinate.longitude) radius:5000];
068  
069     //一定要使用addAnnotation 方法把MKCircle加入进视图,
070     // 否则下面刷新图标的方法是永远不会进入的 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;
071     //切记!!!!
072     [myMapView addAnnotation:circle];
073  
074      //我们需要通过当前用户的经纬度换成出它现在在地图中的地名
075      CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
076     [geocoder reverseGeocodeLocation: _locManager.location completionHandler:
077      ^(NSArray *placemarks, NSError *error) {
078  
079          //得到自己当前最近的地名
080          CLPlacemark *placemark = [placemarks objectAtIndex:0];
081  
082          NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
083  
084          //locatedAt就是当前我所在的街道名称
085          //上图中的中国北京市朝阳区慧中北路
086          [myMapView.userLocation setTitle:locatedAt];
087          [myMapView.userLocation setSubtitle:@"雨松MOMO在这里噢"];
088  
089          //这里是设置地图的缩放,如果不设置缩放地图就非常的尴尬,
090          //只能光秃秃的显示中国的大地图,但是我们需要更加精确到当前所在的街道,
091          //那么就需要设置地图的缩放。
092          MKCoordinateRegion theRegion = { {0.0, 0.0 }, { 0.0, 0.0 } };
093          theRegion.center= myMapView.userLocation.location.coordinate;
094  
095          //缩放的精度。数值越小约精准
096          theRegion.span.longitudeDelta = 0.01f;
097          theRegion.span.latitudeDelta = 0.01f;
098          //让MapView显示缩放后的地图。
099          [myMapView setRegion:theRegion animated:YES];
100  
101          //最后让MapView整体显示, 因为截至到这里,我们已经拿到用户的经纬度,
102          //并且已经换算出用户当前所在街道的名称。
103          myMapView.hidden = false;
104      }];
105  
106 }
107  
108 //定位失败后将进入此方法
109 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { 
110  
111     if ( [error code] == kCLErrorDenied )
112     
113  
114         //第一次安装含有定位功能的软件时
115         //程序将自定提示用户是否让当前App打开定位功能,
116         //如果这里选择不打开定位功能,
117         //再次调用定位的方法将会失败,并且进到这里。
118         //除非用户在设置页面中重新对该软件打开定位服务,
119         //否则程序将一直进到这里。
120         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位服务已经关闭"
121                                                         message:@"请您在设置页面中打开本软件的定位服务"
122                                                        delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
123         [alert show];
124         [alert release];
125         [manager stopUpdatingHeading];
126     }
127     else if ([error code] == kCLErrorHeadingFailure)
128     
129  
130     }
131
132  
133 //在这里我们设置自定义图标来 标志当前我在地图的地方
134 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;
135 {
136     static NSString *identifier = @"com.xys.momo";
137  
138     MKAnnotationView *pin = [ mapView dequeueReusableAnnotationViewWithIdentifier:identifier ];
139     if ( !pin )
140     {
141  
142             pin = [ [ MKAnnotationView alloc ] initWithAnnotation:annotation reuseIdentifier:identifier ];
143             //随便加载了一张ICON
144             //我的icon的大小是48X48 大家可根据仔细的喜好制定自己的icon
145             pin.image = [ UIImage imageNamed:@"0.jpg" ];
146  
147             //在图中我们可以看到图标的上方,有个气泡弹窗里面写着当前用户的位置所在地
148             //原因是这里需要设置了True
149             pin.canShowCallout=YES;
150             //上图气泡的右侧还有一个带箭头的小按钮
151             //这个按钮就是在这里创建的,不过MOMO目前没有写按钮的响应事件喔。
152             //细心的朋友可以自己加上。
153             UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
154             pin.rightCalloutAccessoryView=btn;
155     }
156  
157     pin.annotation = annotation;
158  
159     return pin;
160  
161 }
162  
163 - (void)viewDidUnload
164 {
165     [super viewDidUnload];
166     // Release any retained subviews of the main view.
167 }
168  
169 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
170 {
171     return (interfaceOrientation == UIInterfaceOrientationPortrait);
172 }
173  
174 @end

 

 

最后是本文的源码下载:http://vdisk.weibo.com/s/acdN7

雨松MOMO祝大家学习愉快、工作愉快、生活愉快、互相学习与进步,加油~  话说北京这会应该不下雨了吧??雨停了回家睡觉。 嚯嚯!

———————————-华丽的分割线——————————–

以上方法我在IOS6中使用发现了一点小问题,IOS6使用CLLocationManager定位的时候发现有时候定位到的经纬度是0.0000 所以地图界面中就是一个白屏。那么我将解决的办法贴出来。

1 //定位成功后将进入此方法
2 - (void)locationManager:(CLLocationManager *)manager
3     didUpdateToLocation:(CLLocation *)newLocation
4            fromLocation:(CLLocation *)oldLocation
5 {
6  
7         myMapView.showsUserLocation =YES;
8  
9 }

 

用这个方法来接受当前地图经纬度信息

01 - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
02 {
03  
04     //更新地址,
05     [_locManager stopUpdatingLocation];
06  
07     //设置定位后的自定义图标。
08     MKCircle* circle = [MKCircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(myMapView.userLocation.location.coordinate.latitude, myMapView.userLocation.location.coordinate.longitude) radius:5000];
09  
10     [myMapView addAnnotation:circle];
11  
12     NSLog(@"%f",myMapView.userLocation.location.coordinate.latitude);
13  
14     //我们需要通过当前用户的经纬度换成出它现在在地图中的地名
15     CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
16     [geocoder reverseGeocodeLocation: _locManager.location completionHandler:
17      ^(NSArray *placemarks, NSError *error) {
18  
19          //得到自己当前最近的地名
20          CLPlacemark *placemark = [placemarks objectAtIndex:0];
21  
22          NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
23  
24          //locatedAt就是当前我所在的街道名称
25          //上图中的中国北京市朝阳区慧中北路
26          [myMapView.userLocation setTitle:locatedAt];
27          [myMapView.userLocation setSubtitle:@"你在这里噢"];
28  
29          nowLatitude = myMapView.userLocation.location.coordinate.latitude;
30          nowLongitude = myMapView.userLocation.location.coordinate.longitude;
31  
32          //这里是设置地图的缩放,如果不设置缩放地图就非常的尴尬,
33          //只能光秃秃的显示中国的大地图,但是我们需要更加精确到当前所在的街道,
34          //那么就需要设置地图的缩放。
35          MKCoordinateRegion theRegion = { {0.0, 0.0 }, { 0.0, 0.0 } };
36          theRegion.center= myMapView.userLocation.location.coordinate;
37  
38          //theRegion.center.latitude = targetLatitude;
39          //theRegion.center.longitude = argetLongitude;
40  
41          //缩放的精度。数值越小约精准
42          theRegion.span.longitudeDelta = 0.01f;
43          theRegion.span.latitudeDelta = 0.01f;
44          //让MapView显示缩放后的地图。
45          [myMapView setRegion:theRegion animated:YES];
46  
47          //最后让MapView整体显示, 因为截至到这里,我们已经拿到用户的经纬度,
48          //并且已经换算出用户当前所在街道的名称。
49          //myMapView.hidden = false;
50      }];
51  
52 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值