ios定期获取我的位置并设置按钮以获取我的位置

编程入门 行业动态 更新时间:2024-10-17 00:18:26
本文介绍了ios定期获取我的位置并设置按钮以获取我的位置 - Google地图不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Google Map Module,使用1.9.0 Bundle定期查找我的位置,比如说10秒钟,并创建一个按钮来获取我的位置按钮作为mapview设置之一。

当执行和位置服务处于打开状态时,单击右下角按钮后没有响应,位置管理器不起作用。我可以显示任何使用位置服务的迹象。

我不确定我在设置此地图时缺少什么,因为我严格遵循SDKDemos - ios google演示项目设置我的模块。您能否告诉我设置它的确切方式?

以下是我的代码:

@implementation MapViewController - (bool)isNetworkAvailable { SCNetworkReachabilityFlags标志; SCNetworkReachabilityRef地址; address = SCNetworkReachabilityCreateWithName(NULL,www.apple); 布尔成功= SCNetworkReachabilityGetFlags(address,& flags); CFRelease(地址); bool canReach =成功&& !(flags& kSCNetworkReachabilityFlagsConnectionRequired)&& (flags& kSCNetworkReachabilityFlagsReachable); 返回canReach; } - (void)requestAlwaysAuthorization { CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; //如果状态被拒绝或只授予在使用时,显示一个警告如果(状态== kCLAuthorizationStatusAuthorizedWhenInUse ||状态== kCLAuthorizationStatusDenied){的NSString *标题; title =(status == kCLAuthorizationStatusDenied)? @位置服务已关闭:@后台位置未启用; NSString * message = @要使用后台位置,您必须在位置服务设置中打开始终。 UIAlertView中* alertView = [[UIAlertView中的alloc] initWithTitle:标题消息:消息代表:自 cancelButtonTitle:@ 取消 otherButtonTitles: @设置,无]; [alertView show]; } //用户尚未启用任何位置服务。请求后台授权。 else if(status == kCLAuthorizationStatusNotDetermined){ [locationManager requestAlwaysAuthorization]; $ b - (void)viewDidLoad { [super viewDidLoad]; if([self isNetworkAvailable]){ NSLog(@connected); } else { NSLog(@not connected); } CarArray = [[NSMutableArray alloc] init]; NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; float latitide = [defaults floatForKey:@lati]; float longitude = [defaults floatForKey:@longi]; NSString * desp = [defaults objectForKey:@desp]; GMSMarker * marker = [[GMSMarker alloc] init]; NSLog(@assadsd抵达地图); if(latitide!= 0.00&; longitude!= 0.00){ CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide,longitude); marker.position = CLLocationCoordinate2DMake(position.latitude,position.longitude); camera = [GMSCameraPosition cameraWithLatitude:latitide longitude:longitude zoom:12]; } else { camera = [GMSCameraPosition cameraWithLatitude:22.2855200 longitude:114.1576900 zoom:12]; marker.position = CLLocationCoordinate2DMake(22.2855200,114.1576900); } mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera]; marker.snippet = @HK; mapView_.mapType = kGMSTypeSatellite; mapView_.delegate = self; mapView_.settings.myLocationButton = YES; mapView_.settingspassButton = YES; dispatch_async(dispatch_get_main_queue(),^ { mapView_.myLocationEnabled = YES; }); if(desp.length> 0){ marker.title = desp; //设置位置服务 if(![CLLocationManager locationServicesEnabled]){ NSLog(@请启用位置服务); return; ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){ NSLog(@请授权位置服务); if return; } locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; [locationManager requestWhenInUseAuthorization]; [locationManager requestAlwaysAuthorization]; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.distanceFilter = 5.0f; [mapView_的addObserver:自 forKeyPath:@ myLocation 选项:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)背景:NULL] ; marker.map = mapView_; self.view = mapView_; [locationManager startUpdatingLocation]; GMSCircle * geoFenceCircle = [GMSCircle circleWithPosition:CLLocationCoordinate2DMake(22.2855200,114.1576900)radius:1400]; geoFenceCircle.tappable = true; [geoFenceCircle setFillColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:.5]]; geoFenceCircle.strokeWidth = 13; geoFenceCircle.strokeColor = [UIColor orangeColor]; geoFenceCircle.map = mapView_; //将其添加到地图。 NSLog(@assadsd configured d map); - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)更改上下文:(void *)上下文{ if(!firstLocationUpdate_){ //如果尚未收到第一个位置更新,则跳转到该 // 位置。 firstLocationUpdate_ = YES; CLLocation * location = [change objectForKey:NSKeyValueChangeNewKey]; mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:14]; } } - (void)dealloc { [mapView_ removeObserver:self forKeyPath:@myLocation上下文:NULL]; $ b - (void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker { [mapView明确]; //重新绘制标记 marker.map = mapView; //用新标记创建你的圆圈 GMSCircle * circ = [GMSCircle circleWithPosition:marker.position radius:1000]; circ.fillColor = [UIColor grayColor]; circ.strokeColor = [UIColor redColor]; circ.strokeWidth = 5; circ.map = mapView; } - (空)alertView:(UIAlertView中*)alertView clickedButtonAtIndex:(NSInteger的)buttonIndex {的NSLog(@ buttonIndex:%LD,(长)buttonIndex); if(alertView.tag == 121&& buttonIndex == 1) { //在iOS 8中打开设置应用程序的代码 [ UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; $ b - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog (@ %@,error.userInfo); ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){ NSLog(@请授权位置服务); if return; NSLog(@CLLocationManager error:%@,error.localizedFailureReason); return; $ b - (void)handleDoubleTap { NSLog(@location double tap); } - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightContent; $ b // CLLocationDelegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { CLLocation * location = [locations lastObject]; if(markera == nil){ markera = [[GMSMarker alloc] init]; markera.position = CLLocationCoordinate2DMake(22.86,111.20); markera.groundAnchor = CGPointMake(0.5f,0.97f); //考虑Walker的影子 markera.map = mapView_; }其他{ [CATransaction begin]; [CATransaction setAnimationDuration:2.0]; markera.position = location.coordinate; [CATransaction commit]; } GMSCameraUpdate * move = [GMSCameraUpdate setTarget:location.coordinate zoom:17]; [mapView_ animateWithCameraUpdate:move]; }

我已经在我的项目中设置了pinfo.list的以下参数 p>

NSLocationAlwaysUsageDescription - >位置需要找出你在哪里 NSLocationWhenInUseUsageDescription - >位置需要找出你在哪里

我的测试设备是8.3,iphone 6

解决方案

如果不是,您需要确保 MapViewController 实现 CLLocationDelegate 。 (例如: @interface ViewController:UIViewController< CLLocationManagerDelegate> 在您的 MapViewController.h 文件中)

您可以从GitHub尝试这个工作示例,或此代码片段。

另外,你应该在你的真实设备上测试它,否则你必须在你的XCode模拟器中模拟一个位置(见下图,但它可能并不总是有效)。 img src =i.stack.imgur/7B7pe.pngalt =在这里输入图片描述>

您必须添加 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription 您的info.plist 文件(注意:不要重命名或更改 info.plist 文件的扩展名,扩展名必须为 .plist

/ p>

I am working on Google Map Module , using 1.9.0 Bundle, to find my location on regular basis , say 10 seconds and create a button to get my location button as one of mapview settings

When it comes to the execution and location service is turned on, there are no responses after clicking the right bottom button or not, the location manager is not working. I can show any signs of using location service.

I am not sure what I am missing on setting this map as i follows strictly on the SDKDemos - ios google demo project to set my module. Would you please tell me the exact way to set it ?

The following is my code:

@implementation MapViewController -(bool)isNetworkAvailable { SCNetworkReachabilityFlags flags; SCNetworkReachabilityRef address; address = SCNetworkReachabilityCreateWithName(NULL, "www.apple" ); Boolean success = SCNetworkReachabilityGetFlags(address, &flags); CFRelease(address); bool canReach = success && !(flags & kSCNetworkReachabilityFlagsConnectionRequired) && (flags & kSCNetworkReachabilityFlagsReachable); return canReach; } - (void)requestAlwaysAuthorization { CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; // If the status is denied or only granted for when in use, display an alert if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) { NSString *title; title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled"; NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings"; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Settings", nil]; [alertView show]; } // The user has not enabled any location services. Request background authorization. else if (status == kCLAuthorizationStatusNotDetermined) { [locationManager requestAlwaysAuthorization]; } } - (void)viewDidLoad { [super viewDidLoad]; if([self isNetworkAvailable]){ NSLog(@"connected "); }else { NSLog(@"not connected "); } CarArray = [[NSMutableArray alloc] init]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; float latitide = [defaults floatForKey:@"lati"]; float longitude = [defaults floatForKey:@"longi"]; NSString *desp = [defaults objectForKey:@"desp"]; GMSMarker *marker = [[GMSMarker alloc] init]; NSLog(@"assadsd arrived map"); if(latitide!=0.00&&longitude!=0.00) { CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude); marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude); camera = [GMSCameraPosition cameraWithLatitude:latitide longitude:longitude zoom:12]; }else{ camera = [GMSCameraPosition cameraWithLatitude:22.2855200 longitude:114.1576900 zoom:12]; marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900); } mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera]; marker.snippet = @"HK"; mapView_.mapType = kGMSTypeSatellite; mapView_.delegate = self; mapView_.settings.myLocationButton = YES; mapView_.settingspassButton = YES; dispatch_async(dispatch_get_main_queue(), ^{ mapView_.myLocationEnabled = YES; }); if(desp.length > 0 ){ marker.title = desp; } // Setup location services if (![CLLocationManager locationServicesEnabled]) { NSLog(@"Please enable location services"); return; } if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) { NSLog(@"Please authorize location services"); return; } locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; [locationManager requestWhenInUseAuthorization]; [locationManager requestAlwaysAuthorization]; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.distanceFilter = 5.0f; [mapView_ addObserver:self forKeyPath:@"myLocation" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL]; marker.map = mapView_; self.view = mapView_; [locationManager startUpdatingLocation]; GMSCircle *geoFenceCircle = [GMSCircle circleWithPosition: CLLocationCoordinate2DMake(22.2855200, 114.1576900) radius:1400]; geoFenceCircle.tappable = true; [geoFenceCircle setFillColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:.5]]; geoFenceCircle.strokeWidth = 13; geoFenceCircle.strokeColor = [UIColor orangeColor]; geoFenceCircle.map = mapView_; // Add it to the map. NSLog(@"assadsd configured d map"); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (!firstLocationUpdate_) { // If the first location update has not yet been recieved, then jump to that // location. firstLocationUpdate_ = YES; CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey]; mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:14]; } } - (void)dealloc { [mapView_ removeObserver:self forKeyPath:@"myLocation" context:NULL]; } -(void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker { [mapView clear]; // Re-draw marker marker.map = mapView; // Create your circle with the new marker GMSCircle *circ = [GMSCircle circleWithPosition:marker.position radius:1000]; circ.fillColor = [UIColor grayColor]; circ.strokeColor = [UIColor redColor]; circ.strokeWidth = 5; circ.map = mapView; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog(@"buttonIndex:%ld",(long)buttonIndex); if (alertView.tag == 121 && buttonIndex == 1) { //code for opening settings app in iOS 8 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; } } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"%@",error.userInfo); if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) { NSLog(@"Please authorize location services"); return; } NSLog(@"CLLocationManager error: %@", error.localizedFailureReason); return; } -(void) handleDoubleTap { NSLog(@"location double tap "); } -(UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightContent; } // CLLocationDelegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ CLLocation *location = [locations lastObject]; if (markera == nil) { markera = [[GMSMarker alloc] init] ; markera.position = CLLocationCoordinate2DMake(22.86, 111.20); markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow markera.map = mapView_; }else { [CATransaction begin]; [CATransaction setAnimationDuration:2.0]; markera.position = location.coordinate; [CATransaction commit]; } GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17]; [mapView_ animateWithCameraUpdate:move]; }

I have already set the following parameters of pinfo.list in my project

NSLocationAlwaysUsageDescription -> Location is required to find out where you are NSLocationWhenInUseUsageDescription -> Location is required to find out where you are

My testing device is 8.3 , iphone 6

解决方案

Did your - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ get called?

If not, you need to make sure your MapViewController implements the CLLocationDelegate. (Ex: @interface ViewController : UIViewController<CLLocationManagerDelegate> in your MapViewController.h file)

You can try this working example from GitHub, or the code snippet from this Gist.

Also, you should test it in your real device, otherwise you have to simulate a location in your XCode simulator (see image below, but it might not always work).

You have to add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription to your info.plist file (note: don't rename or change the extension of the info.plist file, the extension has to be .plist):

更多推荐

ios定期获取我的位置并设置按钮以获取我的位置

本文发布于:2023-10-08 01:19:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471092.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   按钮   ios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!