2011-08-11 63 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()