CLLocationCoordinate2D currentCentre不返回lat / long

时间:2012-06-29 20:23:36

标签: iphone ios xcode cocoa-touch

CLLocationCoordinate2D currentCentre;我在ViewDidLoad中使用我的方法时不返回lat / long如果我使用它viewDidAppear它可以工作但是lat / long来自其他地方(不准确)。我想在viewDidLoad或viewDidApear执行[self queryGooglePlaces:@“grocery”];这个我不熟悉这个很好吗

-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//Back Button
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:back];



self.mapView.delegate = self;     



locationManager = [[CLLocationManager alloc] init];


[locationManager setDelegate:self];


[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];


[self.mapView setShowsUserLocation:YES];



firstLaunch=YES;
imageName=[[NSString alloc] init];
imageName=[NSString stringWithFormat:@"park.png"];
[self queryGooglePlaces:@"grocery"];

}


-(void) queryGooglePlaces: (NSString *) googleType
{

// Build the url string we are going to sent to Google. NOTE: The kGOOGLE_API_KEY is a constant which should contain your own API key that you can obtain from Google. See this link for more info:
// https://developers.google.com/maps/documentation/places/#Authentication

NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%@&keyword=%@&sensor=true&key=%@", currentCentre.latitude, currentCentre.longitude, [NSString stringWithFormat:@"%i", currenDist], googleType, kGOOGLE_API_KEY];


NSLog(@"test: %@",url);

//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
//NSLog(url);
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
    [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});

}

我的.h代码

@interface MapViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
 {

CLLocationManager *locationManager;


NSString *imageName;
BOOL firstLaunch;

CLLocationCoordinate2D currentCentre;
int currenDist;


}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
 -(void) queryGooglePlaces: (NSString *) googleType;
@end

但是如果我在按钮中调用它就可以这样工作

- (IBAction)toolbarButtonPresses:(id)sender {


imageName=[[NSString alloc] init];
imageName=[NSString stringWithFormat:@"park.png"];

[self queryGooglePlaces:@"grocery"]; 

}    

2 个答案:

答案 0 :(得分:0)

您需要在[locationManager startUpdatingLocation];中调用viewDidLoad,然后通过查询位置属性检查它是否已返回有效位置 - 检查它是否为零。返回结果可能需要一段时间,因此当其余代码执行时,没有有效值。您可以使用CLLocationManagerDelegate协议中的– locationManager:didUpdateToLocation:fromLocation: – locationManager:didFailWithError:方法来处理此问题。

答案 1 :(得分:0)

请检查设备中运行的代码,而不是在模拟器中 模拟器无法给出正确的纬度/对数位置