7

我有一个 GMSMapView 正确加载并在我的视图控制器中工作

我无法做的是在我的位置周围设置 GMSCameraPosition

这是我的代码:

mapView_.myLocationEnabled = YES;
CLLocation* myLoc = [mapView_ myLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLoc.coordinate.latitude
                                                        longitude:myLoc.coordinate.longitude
                                                             zoom:4];
[mapView_ setCamera:camera];

GPS 已启用并且应用程序具有所有需要的权限,但 myLocation 返回 nil CLLocation,因此cameraWithLatitude:longitude:zoom:得到 0 0 坐标并显示非洲而不是我的实际位置(不在非洲 :))

4

2 回答 2

13

来自官方 Google Maps iOS SDK 文档:

  • (BOOL) myLocationEnabled [读取、写入、分配] 控制是否启用“我的位置”点和精确圆。

默认为否。

  • (CLLocation*) myLocation [读取,分配] 如果启用了我的位置,则显示绘制用户位置点的位置。

如果它被禁用,或者它被启用但没有可用的位置数据,这将为 nil。使用 KVO 可以观察到此属性。

因此,当您设置时mapView_.myLocationEnabled = YES;,它只会告诉mapView您只有在您为属性提供位置值时才显示蓝点myLocation。Google 的示例代码展示了如何使用 KVO 方法观察用户位置。(推荐)您也可以实现该CLLocationManagerDelegate方法,以更新 mapView。

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [mapView animateToLocation:newLocation.coordinate];
    // some code...
}

以下是谷歌地图示例代码中关于如何使用 KVO 更新用户位置的代码。

// in viewDidLoad method...
// Listen to the myLocation property of GMSMapView.
  [mapView_ addObserver:self
             forKeyPath:@"myLocation"
                options:NSKeyValueObservingOptionNew
                context:NULL];
// Ask for My Location data after the map has already been added to the UI.
  dispatch_async(dispatch_get_main_queue(), ^{
    mapView_.myLocationEnabled = YES;
  });

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
  if (!firstLocationUpdate_) {
    // If the first location update has not yet been recieved, then jump to that
    // location.
    firstLocationUpdate_ = YES;
    CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
    mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                     zoom:14];
  }
}
于 2013-07-07T05:28:38.830 回答
-4

尝试使用 MapKit,在VieDidLoadViewWillApper下使用:

myMapView.showsUserLocation = YES;

如果需要,您可以在 IBAction 下添加此简单代码,例如:

- (IBAction)getLocation:(id)sender{

         myMapView.showsUserLocation = YES;

}

我希望这对你有帮助

于 2013-06-28T14:49:18.093 回答