使用Google Map API(GMSMapView)无法获取当前位置 [英] Could not get current location using Google Map API (GMSMapView)
问题描述
我尝试使用Google Map API获取从当前位置到其他地点的路线.当我手动输入起点和终点时,一切都OK.但是,当我尝试将原点设置为当前位置时,该位置为null,如下所示:
mainMap = [[GMSMapView alloc] initWithFrame:CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height)];GMSCameraPosition * camera = [GMSCameraPosition cameraWithTarget:[mainMap.myLocation坐标] zoom:13];mainMap.camera = camera;mainMap.myLocationEnabled = YES;//< ----蓝点出现在地图上:这正是我的位置[self.view addSubview:mainMap];//获取我的位置CLLocation * myLocation = mainMap.myLocation;//< ----- NULL
有没有人知道我的问题在这里?非常感谢
问题是:获取位置是异步的,您如何执行该操作,希望它一直阻塞到该位置为止……这不是它的工作原理>
您必须在地图中添加KVO观察员,并在myLocation中添加观察员.
然后,当您的observe方法被调用时,您将获得myLocation.
(蓝点也是如此:))
-(void)viewDidLoad {//...[self.mapView addObserver:self forKeyPath:"myLocation"选项:0上下文:无];}-(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 = [对象myLocation];//...}}
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
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];
//...
}
}
这篇关于使用Google Map API(GMSMapView)无法获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!