iphone app - 如何只获取一次当前位置并将其存储以用于另一个功能?

Posted

技术标签:

【中文标题】iphone app - 如何只获取一次当前位置并将其存储以用于另一个功能?【英文标题】:iphone app - how to get the current location only once and store that to be used in another function? 【发布时间】:2012-11-09 14:16:44 【问题描述】:

过去两周我一直在研究这个问题 - 我有一个应用程序,可以在地图上显示从起点到终点的清晰路线。目的地是用户地址(由用户在我们设置的设置菜单中定义/输入),如果我硬编码起点,地图、路线和应用程序都可以正常工作。一旦我尝试实现任何涉及使用 cllocation 或 cllocationmanager 的东西,它就会崩溃并给我一个线程错误(有 3 个)。

这是当前视图控制器的头文件和实现文件:

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "MapView.h"
#import "Place.h"
#import <CoreLocation/CoreLocation.h>


@interface HomeMapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>

    IBOutlet UILabel *HomeAddressLabel;



@property (weak, nonatomic) IBOutlet MKMapView *MapView;
@property (strong, nonatomic) IBOutlet CLLocationManager *location;
@end

实现文件:

#import "HomeMapViewController.h"



@interface HomeMapViewController ()

@end


@implementation HomeMapViewController
@synthesize MapView;
@synthesize location;
double lat = 37.331706;
double lon = -122.030598;
- (id)initWithNibNameNSString *)nibNameOrNil bundleNSBundle *)nibBundleOrNil

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
        // Custom initialization
    
    return self;



- (void)viewDidLoad

    //Retrieve saved address before view loads
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *HomeAddress = [defaults objectForKey:@"HomeAddress"];
    NSString *HomeCity = [defaults objectForKey:@"HomeCity"];
    NSString *HomeProvince = [defaults objectForKey:@"HomeProvince"];
    NSString *HomeZip = [defaults objectForKey:@"HomeZip"];
    NSString *HomeCountry = [defaults objectForKey:@"HomeCountry"];
    NSString *HomeAddressFull = [NSString stringWithFormat:@"%@, %@, %@, %@, %@", HomeAddress, HomeCity, HomeProvince, HomeZip, HomeCountry];

    //Set address label to saved address values
    HomeAddressLabel.text = HomeAddressFull;



    //Map Route Code

        MapView* mapView = [[MapView alloc] initWithFrame:
                        CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        //Shows user location

    [self.MapView setShowsUserLocation:YES];
    //set which mapview to show
        [self.MapView addSubview:mapView];

    self.location = [[CLLocationManager alloc]init];
    location.delegate = self;
    location.desiredAccuracy=kCLLocationAccuracyBest;
    location.distanceFilter = kCLLocationAccuracyBestForNavigation;//constant update of device location
    [location startUpdatingLocation];


    Place* start = [[Place alloc] init];
    start.name = @"Start Location";
    start.description = @"You started here.";
    //^should be changed to current location once that is implemented
    //start.latitude =    37.331706;
    //start.longitude = -122.030598;
    start.latitude = lat;
    start.longitude = lon;
    //start.latitude = location.location.coordinate.latitude;
    //start.longitude = location.location.coordinate.longitude;


    //Geocoder Code
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:HomeAddressFull completionHandler:^(NSArray *placemarks, NSError *error) 
        if (error) 
            NSLog(@"Error: %@", [error localizedDescription]);
            return;
        

        for (id object in placemarks) 
            CLPlacemark *placemark = object;



            Place* destination = [[Place alloc] init];
            destination.name = @"Destination";
            destination.description = [NSString stringWithFormat:@"%@, %@, %@", HomeAddress, HomeCity, HomeProvince];
            destination.latitude = placemark.location.coordinate.latitude;
            destination.longitude = placemark.location.coordinate.longitude;

            [mapView showRouteFrom:start toestination];
        
    ];


    [super viewDidLoad];



- (void)locationManagerCLLocationManager *)manager didUpdateToLocationCLLocation *)newLocation fromLocationCLLocation *)oldLocation
    [manager stopUpdatingLocation];





//************NEW METHOD
-(void)locationManagerCLLocationManager *)manager didFailWithErrorNSError *)error
    NSString *msg = @"Error obtraining location:";
    UIAlertView *alert;
    alert = [[UIAlertView alloc]
             initWithTitle:@"Error"
             message:msg delegate:self
             cancelButtonTitle:@"OK"
             otherButtonTitles: nil];
    [alert show];



- (void)viewDidUnload

    [self setMapView:nil];
    HomeAddressLabel = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.


- (BOOL)shouldAutorotateToInterfaceOrientationUIInterfaceOrientation)interfaceOrientation

    return (interfaceOrientation == UIInterfaceOrientationPortrait);



@end

我基本上想问是否有人可以帮助阐明我如何获取用户当前位置坐标并将它们存储为 start.latitude 和 start.longitude 值,以便路线显示从用户当前位置到他们的目的地。路线不应该在用户移动时自行更新,我只想在用户当前位置和目的地(正如我所做的那样)上有一个注释/地标,然后蓝点(又名用户)将能够看到自己沿着他们要走的路线前进。我已经尝试了这里的所有建议 - 有些根本没有用,有些只工作了一次,然后它再次失败(即使在重置模拟器内容之后!)。一些链接是相关的,但非常过时,所以那里的方法不起作用。

在这里我想获取用户当前的位置坐标将是这个功能更容易的任务!

【问题讨论】:

【参考方案1】:

.h 文件

#import <CoreLocation/CoreLocation.h>

@property (nonatomic,retain) CLLocationManager *locationManager;

.m 文件

- (NSString *)deviceLocation 

    NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
    return theLocation;


- (void)viewDidLoad

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.distanceFilter = kCLDistanceFilterNone; 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [self.locationManager startUpdatingLocation];

【讨论】:

谢谢!!我最终使用 NSUserDefaults 来存储来自位置管理器的位置,但我没有使用对象键,而是使用了纬度和经度的双键。如果其他人正在这样做 - 您需要先在屏幕中获取用户位置,然后再在地图中显示路线。这样,该函数就拥有了 viewdidload 所需的一切,否则它会崩溃——这就是我所拥有的。对不起,我不能投票,还是个新手。【参考方案2】:

最简单的方法是将起始当前位置存储在 NSUserDefaults 中

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:latitude forKey:@"starLatitude"];
    [defaults setObject:longitude forKey:@"starLongitude"];
[defaults synchronize];

那么就可以通过以下方式获取经纬度:

NSString *lati = [defaults objectForKey:@"starLatitude"];

【讨论】:

对不起,我对此很陌生 - 我如何将纬度和经度存储为对象??

以上是关于iphone app - 如何只获取一次当前位置并将其存储以用于另一个功能?的主要内容,如果未能解决你的问题,请参考以下文章

如何在iphone上的地图中获取当前位置

提示输入核心位置时如何获得用户响应?

如何在iphone中获取当前位置的纬度经度?

如何通过代码获取 iPhone 的当前位置?

如何通过iphone应用程序中的代码获取用户的当前位置?

如何使用 iphone 获取建筑物内的当前位置?