2011-08-11 62 views
8

我有哪些缩放到使用viewDidLoad当前位置的MapView类:转至/缩放到当前位置的功能(MapKit)

#define METERS_PER_MILE 1609.344 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    mapView.showsUserLocation=TRUE; 

    // zoom to a specific area 
    CLLocationCoordinate2D zoomLocation; 
    zoomLocation.latitude = -28.994167; 
    zoomLocation.longitude = 134.866944; 

    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 1900*METERS_PER_MILE, 1900*METERS_PER_MILE); 
    MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];  

    // make sure the Google water mark is always visible 
    mapView.autoresizingMask = 
    (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); 

    [mapView setRegion:adjustedRegion animated:YES];   

    mapView.delegate=self; 

    searchBar.delegate = self; 
} 

这工作得很好。我添加了一个搜索栏和一个功能来跳转到特定的地址位置。这工作也很好。我现在想添加一个按钮跳回到当前位置。你能帮我一下吗?

干杯

回答

10

您需要在地图的中心设置为当前位置,该按钮的点击。说,像这样的:

- (IBAction)showCurrentLocation {   
    [mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES]; 
} 
+0

添加yourMKMapView.showsUserLocation = true是有一个叫setCenter功能? – carbonr

+0

@carbonr是的,有 –

+12

[mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES]; – carbonr

2

你也可以尝试:

mapView.userTrackingMode=YES; 
mapView.userTrackingMode=NO; 
+0

只要确保在viewDidAppear方法或更高版本中调用此方法。 – lehn0058

+1

'userTrackingMode'不是'BOOL'。这是一个'MKUserTrackingMode'枚举。只有将它设置为YES/NO的原因是因为YES等于MKUserTrackingModeFollow而NO等于MKUserTrackingModeNone。但'userTrackingMode'也可以是第三个值'MKUserTrackingModeFollowWithHeading'。 – Anna

0
- (void)showCurrentLocation{ 

    MKMapPoint annotationPoint = MKMapPointForCoordinate(self.mapView.userLocation.coordinate); 
    MKMapRect zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.0, 0.0); 
    [self.mapView setVisibleMapRect:zoomRect animated:YES]; 
} 
1

您可以将此IBAction为链接到您的UIButton, 它会继续前进当前位置的地图和放大的它。

@IBOutlet weak var mapView: MKMapView! 

@IBAction func zoomToUserCurrentLocation(sender: AnyObject) { 
    if self.mapView != nil { 
     self.mapView.setRegion(MKCoordinateRegionMake(
      self.mapView.userLocation.coordinate, 
      MKCoordinateSpanMake(0.1, 0.1) 
     ), animated: true) 
    } 
} 

MKCoordinateSpan定义了地图区域跨越的区域,这些值越小,缩放地图越近。

0

为SWIFT

添加按钮动作此行yourMKMapView.setUserTrackingMode(.follow, animated: true)

确保您在viewDidLoad()