Jonny Vu
Jonny Vu

Reputation: 1428

Could not get current location using Google Map API (GMSMapView)

I try to get the direction from current location to other point using Google Map API. Everything is OK when i input the origin point and destination point manually. But, when i try to set the origin point as current location, the location is null as the following code:

mainMap=[[GMSMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:[mainMap.myLocation coordinate] zoom:13];
mainMap.camera=camera;
mainMap.myLocationEnabled=YES; // <---- The blue point appear on map: it's exactly my location

[self.view addSubview:mainMap];

//Get mylocation
CLLocation *myLocation = mainMap.myLocation; // <----- NULL

Is there any body know what is my problem here? Tks a lot

Upvotes: 0

Views: 4900

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50139

The thing is: Getting a location is asynchronous and how you do it is expect it to block till its there... which is not how it works

you have to add a KVO observer inn the map and observer myLocation.
Then when your observe method gets called, you get the myLocation.

(that's how the blue dot works too :))

- (void)viewDidLoad {
    //...
    [self.mapView addObserver:self forKeyPath:"myLocation" options:0 context:nil];
}
- (void)dealloc {
    [_mapView removeObserver:self forKeyPath:@"myLocation"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"myLocation"]) {
        CLLocation *l = [object myLocation];
        //...
    }
}

Upvotes: 3

Related Questions