2011-08-01 62 views

回答

13

實施CLLocationManagerDelegate寫此功能,在你的viewController的viewDidLoad方法調用它。

-(void)startLocationManager 
{ 
    CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate=self; 
    locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation; 
    [locationManager startUpdatingLocation]; 
} 

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{  
    CLLocationCoordinate2D coordinate = [newLocation coordinate]; 
    double dblLatitude = coordinate.latitude; 
    double dblLongitude = coordinate.longitude;  
} 
+1

非常感謝您在iOS 6中使用 –

+0

didUpdateToLocation已棄用,因此請使用** didUpdateLocations ** – swiftBoy

4

如果您使用CLLocationmanager,請確保您檢查是否首先啓用位置服務。我想這樣做是爲了獲得當前位置:

if ([CLLocationManager locationServicesEnabled]) 
{ 
    CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
    [locationManager startUpdatingLocation]; 

    CLLocationCoordinate2D *currentLocation = locationManager.location; 

    [locationManager stopUpdatingLocation]; 
    [locationManager release]; 
} 

如果您正在使用的MapView,您可以用獲取當前位置:

[mapView setShowsUserLocation:YES]; 
CLLocationCoordinate2D *currentLocation = mapView.userLocation.coordinate;