使用CLLocationCoordinate2D获取当前位置

iOS*_*Dev 1 iphone objective-c cllocationmanager ios

我试图使用CLLocationCoordinate2D获取用户的当前位置.我希望格式的值如

CLLocationCoordinate2D start = {-28.078694,153.382844};

所以我可以使用它们如下:

 NSString *urlAddress = [NSString 
       stringWithFormat:@"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",  
       start.latitude, start.longitude, 
       destination.latitude, destination.longitude];  
Run Code Online (Sandbox Code Playgroud)

我用了

CLLocation *location = [[CLLocation alloc]init ];
CLLocationDegrees currentLatitude = location.coordinate.latitude;
CLLocationDegrees currentLongitude = location.coordinate.longitude;
Run Code Online (Sandbox Code Playgroud)

获得当前的lat和long.

但是当我尝试测试时,我得到了0.000.我在iPhone 4s上测试.

如果有任何示例代码,那就太棒了.

Mud*_*pai 15

首先添加CoreLocation框架,然后使用以下代码...并且您的viewController必须实现CLLocationManagerDelegate

-(void)findCurrentLocation
{

    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    if ([locationManager locationServicesEnabled])
    {
        locationManager.delegate = self; 
        locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
        locationManager.distanceFilter = kCLDistanceFilterNone; 
        [locationManager startUpdatingLocation];
    }


    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];

    NSString *str=[[NSString alloc] initWithFormat:@" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
    NSLog(@"%@",str);


}
Run Code Online (Sandbox Code Playgroud)

  • 在这个例子中,`[locationManager location]`可能会返回`nil`或非常旧的位置.获取当前位置的最佳方法是等待`locationManager`将回调消息发送给其委托.但是仍然通过回调消息传递的位置可能是旧的,因此,您需要始终检查位置的时间戳. (3认同)

Vib*_*oti 7

在AppDelegate.h中声明以下变量.并实施

CLLocationManagerDelegate delegate.

CLLocationManager *locationManager;
CLLocation *currentLocation;
Run Code Online (Sandbox Code Playgroud)

在AppDelegate.hm文件中编写以下代码.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {       

    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    self.currentLocation = newLocation;
    self.currentLat =  newLocation.coordinate.latitude; 
    self.currentLong =  newLocation.coordinate.longitude; 
}
Run Code Online (Sandbox Code Playgroud)