GMSMapView myLocation没有给出实际位置

Zer*_*rho 7 google-maps objective-c ios google-maps-sdk-ios

我有一个GMSMapView正确加载并在我的viewcontroller中工作

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

这是我的代码:

mapView_.myLocationEnabled = YES;
CLLocation* myLoc = [mapView_ myLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLoc.coordinate.latitude
                                                        longitude:myLoc.coordinate.longitude
                                                             zoom:4];
[mapView_ setCamera:camera];
Run Code Online (Sandbox Code Playgroud)

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

Jin*_*ing 13

从官方Google Maps iOS SDK文档:

  • (BOOL)myLocationEnabled [read,write,assign]控制是否启用"我的位置"点和精度圆.

默认为NO.

  • (CLLocation*)myLocation [read,assign]如果启用了"我的位置",则显示正在绘制用户位置点的位置.

如果它被禁用,或者它已启用但没有可用的位置数据,则为零.使用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...
}
Run Code Online (Sandbox Code Playgroud)

以下是Google地图示例代码中有关如何使用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];
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 不敢相信Google没有在GMSMapViewDelegate中包含一个方法,在这种情况下使用KVO有点骇客... (2认同)

Bla*_*eep -4

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

myMapView.showsUserLocation = YES;
Run Code Online (Sandbox Code Playgroud)

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

- (IBAction)getLocation:(id)sender{

         myMapView.showsUserLocation = YES;

}
Run Code Online (Sandbox Code Playgroud)

我希望这对你有帮助