如何同步移动标记和相机,并始终将标记放置在相机位置的中心



我想让GMSMarker移动到相机。这是我的代码

 -(void)addMap {
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
                                                                longitude:longitude
                                                                     zoom:15];
        GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
        CGRect newFrame = CGRectMake( 0, 0, [Util window_width],[Util window_height]);
        mapView = [GMSMapView mapWithFrame:newFrame camera:camera];
        mapView.delegate = self;
        mapView.myLocationEnabled = YES;
        GMSMarker *marker = [[GMSMarker alloc] init];
        marker.position = camera.target;
        marker.snippet = @"Hello World";
        marker.icon =[Util imageWithImage:[UIImage imageNamed:@"set_address.png"] scaledToSize:CGSizeMake(170, 65)];
        marker.appearAnimation = kGMSMarkerAnimationPop;
        marker.map = mapView;
        [self.MapContentView addSubview:mapView];

     }

我在地图上有一个标记,如果用户不滚动地图,它通常位于地图的中心。

当用户滚动地图时,我希望标记与相机一起移动到新的位置,因此它始终位于地图的中心。

我尝试下面的代码

-(BOOL) mapView:(GMSMapView *) mapView didTapMarker:(GMSMarker *)marker
{
    [mapView animateToLocation:marker.position];

    return YES;
}

- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position
{
    marker.position = camera.target;
    marker.appearAnimation = kGMSMarkerAnimationPop;
    NSLog(@"camera.target.latitude %f,%f",camera.target.latitude,camera.target.longitude);
    latitude=camera.target.latitude;
    longitude=camera.target.longitude;
}

你可以试试:

- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture
{
    [self recenterMarkerInMapView:mapView];
}
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position
{
    [self recenterMarkerInMapView:mapView];
}
- (void)recenterMarkerInMapView:(GMSMapView *)mapView
{
    // Get the center of the mapView
    CGPoint center = [mapView convertPoint:mapView.center fromView:self.view];
    // Reset the marker position so it moves without animation
    [mapView clear];
    marker.appearAnimation = kGMSMarkerAnimationNone;
    marker.position = [mapView.projection coordinateForPoint:center];
    marker.map = mapView;
}

将选定的标记移动到mapView的中心。

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {  
      mapView.animate(toLocation: marker.position)   
      return true 
 }

最新更新