2012-02-20 3 views
1

Я хочу получить текущее местоположение пользователя из своего iPhone-приложения. Я хочу показать текущее местоположение пользователя, например название страны, широту и долготу в моем приложении. А также я хочу показать местоположение на карте Google. Я также пробовал поиск Google, но не могу получить точный ответ. У меня есть информация, которая должна была использовать CLLocationManager в моем приложении, чтобы отслеживать местоположение. Как я могу это использовать? Я загрузил одно приложение из Apple Documents. Вот ссылка: https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.htmlКак получить текущее местоположение пользователя по коду в приложении iphone?

Не могли бы вы помочь мне в этом? Заранее спасибо.

+0

Возможный дубликат [Как получить текущее местоположение от пользователя в iOS] (http: // stackoverflow.com/questions/4152003/how-can-i-get-current-location-from-user-in-ios) – Pascal

ответ

1

1) У меня есть получить информацию, которая должен был использовать CLLocationManager в своем приложении, чтобы отслеживать местоположение. Как я могу это использовать?

в файле .h

#include <CoreLocation/CLLocationManagerDelegate.h> 
#include <CoreLocation/CLError.h> 
#include <CoreLocation/CLLocation.h> 
#include <CoreLocation/CLLocationManager.h> 

CLLocationManager * myLocationManager; 

CLLocation   * myLocation; 

в .m файл: -

-(void)findMyCurrentLocation 
    {   

    self.myLocationManager = [[[CLLocationManager alloc] init] autorelease]; 
    [[self myLocationManager] setDelegate:self ]; 
    [myLocationManager startUpdatingLocation]; 

    double latitude=34.052234; 
    double longitude=-118.243685; 

    CLLocation *defaultLocation =[[CLLocation alloc] initWithLatitude:latitude longitude:longitude]; 
    [self setMyLocation:defaultLocation]; 
    [defaultLocation release]; 

    if([CLLocationManager locationServicesEnabled]) 
    { 
     NSLog(@"Location Services Enabled...."); 
     locationServicesEnabled=TRUE; 
     UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Information" 
                 message:@"Fetching your current location." 
                 delegate:self 
               cancelButtonTitle:@"OK" 
               otherButtonTitles:nil ]; 
     [alert release]; 
    } 
    else 
    { 
     NSLog(@"Location Services Are Not Enabled...."); 
     locationServicesEnabled=FALSE; 
     UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Information" 
                 message:@"Location service is not enable. Please enable it from settings." 
                 delegate:self 
               cancelButtonTitle:@"OK" 
               otherButtonTitles:nil ]; 
     [alert release]; 
    } 

     } 

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
    { 
     [self setMyLocation:newLocation]; 

    NSString *tempLat = [ NSString stringWithFormat:@"%3.6f" , (newLocation.coordinate.latitude) ]; 
    NSString *tempLong= [ NSString stringWithFormat:@"%3.6f" , (newLocation.coordinate.longitude)]; 

    appDelegate.curlat = tempLat; 
    appDelegate.curlong = tempLong; 
    } 

    - (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error 
    { 
    printf("\nerror"); 
    UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:@"Error" 
                message:@"Error while getting your current location." 
                delegate:self 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil ]; 

    [alert release]; 
    } 

2). Я хочу показать текущее местоположение пользователя, например, имя страны в моем приложении.

Для этого вы можете использовать Google's Reverse Geo coding ИЛИ MKReverseGeocoder

+0

Проверить обновленный ответ – Maulik

+0

Просто заметьте, MKReverseGeocoder больше не существует, вам нужно использовать CLGeocoder и использовать функцию reverseGeocode – MCKapur

1

это должно сделать большинство из них ..

http://www.highoncoding.com/Articles/804_Introduction_to_MapKit_Framework_for_iPhone_Development.aspx

, чтобы получить информацию о местоположении, необходимо использовать MKReverseGeocoder

https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323

0

сначала создать экземпляр MKMapView

Чтобы получить широту пользователя и долготу:

В вашей viewDidLoad

[yourMapView setShowsUserLocation:YES]; 

CLLocationCoordinate2D userCoord; 

userCoord.latitude=map_view.userLocation.coordinate.latitude; 
userCoord.longitude=map_view.userLocation.coordinate.longitude; 

//NSLogging these on simulator will give you Cupertino or whatever location you set in location simulation. 

И название страны вам нужно будет reversegeocoding вы можете посмотреть на ссылки класса здесь

https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323

ИЛИ

Если MKReverseGeoCoding становится слишком сложным вы можете использовать Yahoo, reversegeocoder

http://where.yahooapis.com/geocode?q=%f,%f&gflags=R&appid=yourAppId, те 2% f будут userCoord.longitude и userCoord.latitude.

0

Да, вы можете использовать CLGeoCoder. Но CLGeaCoder не будет предоставлять информацию о конфиденциальности в других странах, например, в Индии и т. Д. Поэтому лучше использовать обратное геокодирование Google SVGeoCoder. SVGeoCoder имеет приятную реализацию, чтобы получить местоположение с goolePlaceAPI.