0

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

1
  • mainMap.myLocation is only set asynchronously because it isn't designed to block (which would be bad)
    – Daij-Djan
    Dec 16, 2013 at 13:18

1 Answer 1

3

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.