Как загрузить карту с полученным текущим местоположением в iphone? - PullRequest
1 голос
/ 17 февраля 2010

Я новичок в разработке для iphone. Я создаю приложение карты. У меня есть панель инструментов под видом карты с кнопкой на ней. При нажатии на кнопку она отображается как предупреждение для загрузки текущего местоположения. Хава дал код, чтобы найти текущее местоположение

 -(IBAction) gosearch : (id) sender{
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self; 
[locationManager startUpdatingLocation];
}

Для меня это не отображение предупреждения. Что мне делать? Пожалуйста, помогите мне. Спасибо.

Ответы [ 3 ]

1 голос
/ 17 февраля 2010

Вам нужно, чтобы ваш класс контроллера реализовал протокол CLLocationManagerDeligate. Это будет означать, что он получит уведомление об ошибках или когда будет опубликовано местоположение (например, locationManager: didUpdateToLocation: fromLocation:)

Затем вы можете передать длинный / лат и радиус обзора, необходимые для MapView

0 голосов
/ 17 февраля 2010

Я не уверен, что полностью понимаю ваши вопросы, но вот что я сделал, чтобы использовать диспетчер местоположений.

Сначала я объявляю класс, который реализует CLLocationManagerDelegate

@interface GPSComponent <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

Тогда в классе у меня есть:

- (id) init {
    locationManager = [[CLLocationManager alloc] init];

    // Provide the best possible accuracy (this is the default; just want to write some code).
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;

    // Must move at least 100 meters to get a new location update (default is get all notifications).
    locationManager.distanceFilter = 100;   

    locationManager.delegate = self;

    [locationManager startUpdatingLocation];
}

#pragma mark -
#pragma mark CLLocationManagerDelegate methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // If you are about 400 miles south off the coast of Ghana, we might be ignoring your location information. We apologize.
    // This is a lazy way to check for failure (in which case the struct is zeroed out).
    if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
        NSLog(@"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
        if (currentLocation != nil) {
            [currentLocation release];
        }
        currentLocation = newLocation;
        [currentLocation retain];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location Manager error");
}

Затем, чтобы отобразить карту с местоположением пользователя:

// Pull out the longitude and latitude and invoke google maps
- (IBAction)mapItButtonPressed {
    NSString *url = [NSString stringWithFormat: @"http://maps.google.com/maps?q=%f,%f", (float)currentLocation.coordinate.latitude, (float)currentLocation.coordinate.longitude]; 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
} 
0 голосов
/ 17 февраля 2010

Убедитесь, что для просмотра предупреждений это выглядит так -

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Current Location" message:@"Show Current Location?" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK"];
        [alert show];

, а также

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        map.showsuserlocation = YES;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...