iPhone应用程序 - 如何仅获取当前位置并存储以在另一个函数中使用?

10

我已经花了过去两个星期的时间来开发这个应用程序 - 我有一个可以在地图上显示从起点到目的地的可读路线的应用程序。目的地是用户地址(由用户在我们设置的菜单中定义或输入),如果我硬编码起点,地图、路线和应用程序都可以正常工作。但一旦我尝试实现任何涉及使用cllocation或cllocationmanager的内容,它就会崩溃并给我三个线程错误。

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

#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

我基本上想问一下是否有人可以帮助解决如何获取用户当前位置坐标并将其存储为起点纬度和起点经度值,以便路径显示从用户当前位置到其目的地的路径。路线不应随着用户移动而更新,我只想在用户当前位置和目的地(我已经有了)上有一个注释/地标,然后蓝点(即用户)将能够看到自己沿着要走的路线移动。我尝试了这里所有的建议-有些根本没有起作用,有些只起作用一次,然后再也无法工作(即使重置模拟器内容!)。有些链接虽然相关但非常过时,所以那里的方法不起作用。

我还以为获取用户当前位置坐标会是此功能中更容易的任务呢!

2个回答

15

.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];
}

1
谢谢!最终我使用NSUserDefaults存储了位置管理器中的位置,但是我用了双键而不是对象键来表示纬度和经度。如果其他人也在做这个 - 你需要在地图上显示路线之前,在屏幕上抓取用户位置。这样该函数就有了它所需的所有内容,在viewdidload中否则会崩溃 - 这就是我的情况。很抱歉我不能点赞,因为我还是新手。 - Fee

5

简单的方法是将起始电流位置存储在NSUserDefaults中。

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

然后您可以按照以下方式获取纬度和经度:

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

1
抱歉,我对此还比较新 - 我该如何将纬度和经度存储为对象? - Fee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接