在Google地图上显示当前位置

时间:2014-05-22 20:06:29

标签: ios google-maps-sdk-ios gmsmapview cllocationcoordinate2d

我有一个iOS应用,它使用Google Maps SDK在我的应用中显示地图。

我设法让地图显示但我不知道如何将相机或标记设置为用户当前位置。

我已经对坐标进行了硬编码,只是为了测试地图的工作情况,但我现在仍然坚持如何显示用户的当前位置。

以下是我将相机置于坐标中心的代码

- (void)viewDidLoad
{
    [super viewDidLoad];

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:47.995602 longitude:-78.902153 zoom:6];

    self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

    self.mapView.myLocationEnabled = YES;
    self.mapView.mapType = kGMSTypeNormal;
    self.mapView.accessibilityElementsHidden = NO;
    self.mapView.settings.scrollGestures = YES;
    self.mapView.settings.zoomGestures = YES;
    self.mapView.settings.compassButton = YES;
    self.mapView.settings.myLocationButton = YES;
    self.mapView.delegate = self;
    self.view = self.mapView;

    [self placeMarkers];
}

以下是在坐标

处显示标记的代码
-(void)placeMarkers
{
    GMSMarker *marker = [[GMSMarker alloc] init];

    marker.position = CLLocationCoordinate2DMake(47.995602, -78.902153);
    marker.title = @"PopUp HQ";
    marker.snippet = @"Durham, NC";
    marker.icon = [GMSMarker markerImageWithColor:[UIColor blueColor]];
    marker.opacity = 0.9;
    marker.map = self.mapView;
}

我试图获得如下当前位置:

CLLocationCoordinate2D *myLocation = self.mapView.myLocation.coordinate;

但是我收到了错误:

  

使用不兼容类型'CLLocationCoordinate2D'的表达式初始化'CLLocationCoordinate2D'

如何将当前位置传递给相机以及标记?

2 个答案:

答案 0 :(得分:4)

CLLocationCoordinate2D只是一个包含纬度和经度的结构,所以你可以简单地使用

CLLocationCoordinate2D myLocation = self.mapView.myLocation.coordinate;

使用KVO观察myLocation的变化也是值得的,因为mapView可能还没有有效的位置。

进一步解释KVO:

您可以为myLocation属性添加观察者,如下所示:

[self.mapView addObserver:self
          forKeyPath:@"myLocation"
             options:(NSKeyValueObservingOptionNew |
                      NSKeyValueObservingOptionOld)
             context:NULL];

然后,您应该实现以下方法:

- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context {
    if ([keyPath isEqualToString:@"myLocation"]) {
//            NSLog(@"My position changed");
    }
}

然后,您可以安全地访问self.mapView.myLocation.coordinate,知道该位置有效。

当取消分配mapview时,不要忘记将自己移除为观察者:

[self.mapView removeObserver:self forKeyPath:@"myLocation"];

正如Saxon已经提到的那样,mapview将显示它自己当前的位置指示器。您将添加的标记将另外显示,但是当您创建标记时,mapview可能还没有有效位置,因此它将被添加到纬度/经度0,0处于中间位置海洋。

答案 1 :(得分:1)

当您将myLocationEnabled设置为YES时,地图会自动在您当前位置添加标记。所以你可能不需要自己添加?

设备和您的应用需要一段时间才能确定您的位置。当它启动时它可能还不知道你的位置,所以默认为纬度/纬度为零,这是非洲的。

正如NigelG所说,你可以在myLocation属性上使用KVO来找出位置更新的时间。

相关问题