zoomLevel и mapCenter в MKMapView

Я создаю приложение «Карта» на iPhone, используя MKMapView.

Я успешно нашел свои current location и zoom в этой точке следующим образом:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.mapView.delegate = self;

    self.locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];

    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

    [self.mapView setShowsUserLocation:YES];
}

-(void) mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MKAnnotationView *annotationView = [views objectAtIndex:0];
    id<MKAnnotation> mp = [annotationView annotation];

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate], 1550, 1550);
    [self.mapView setRegion:region animated:YES];
}

Проблема, которую я хочу решить:

У меня location на map (этот код в viewDidLoad):

CLLocationCoordinate2D location = [self getLocationFromAddressString:@"San Francisco, CA, United States"];
//    location.latitude = 37.78608;
//    location.longitude = -122.407398;

    MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Store location" coordinate:location];
    [self.mapView addAnnotation:mapAnnotation];

а это mapViewAnnotation:

@implementation MapViewAnnotation

@synthesize title = _title;
@synthesize coordinate = _coordinate;

- (id) initWithTitle:(NSString *) t coordinate:(CLLocationCoordinate2D) c {
    self = [super init];
    if(self) {
        _title = t;
        _coordinate = c;
    }
    return self;
}
@end

Я хочу иметь правильные zoomLevel и mapCenter для этого location и моего current location.

Я мог бы успешно сделать это в Android, используя MapController.zoomToSpan(). Как я могу исправить это в iPhone Map?


person Ali    schedule 04.10.2012    source источник


Ответы (2)


создать массив местоположений и после этого центра карты со всеми AnnotationPins

-(void) RoutscenterMap 
{
        MKCoordinateRegion region;

        CLLocationDegrees maxLat = -90;
        CLLocationDegrees maxLon = -180;
        CLLocationDegrees minLat = 90;
        CLLocationDegrees minLon = 180;
        for(int idx = 0; idx < arrLocation.count; idx++)// here use your array or points
        {
            CLLocation* currentLocation = [arrLocation objectAtIndex:idx];
            if(currentLocation.coordinate.latitude > maxLat)
                maxLat = currentLocation.coordinate.latitude;
            if(currentLocation.coordinate.latitude < minLat)
                minLat = currentLocation.coordinate.latitude;
            if(currentLocation.coordinate.longitude > maxLon)
                maxLon = currentLocation.coordinate.longitude;
            if(currentLocation.coordinate.longitude < minLon)
                minLon = currentLocation.coordinate.longitude;
        }

        region.center.latitude     = (maxLat + minLat) / 2;
        region.center.longitude    = (maxLon + minLon) / 2;
        region.span.latitudeDelta  = (maxLat - minLat) * 2;
        region.span.longitudeDelta = (maxLon - minLon) * 2;

        [mapView setRegion:region animated:YES];
    }

также вы можете добавить местоположение в массив, как показано ниже...

 CLLocation *temploc=[[CLLocation alloc]initWithLatitude:latitude longitude:longtitude];
 [arrLocation addObject:temploc];

после этого используйте этот массив для центрирования карты

я надеюсь, что это поможет вам ...

:)

person Paras Joshi    schedule 04.10.2012
comment
Это как-то жестко запрограммировано. вы работали с MapController.zoomToSpan() в Android? дело в том, что я хочу центрировать, увеличить масштаб между моим текущим местоположением и CLLocationCoordinate2D location, ваш код мне в этом не помогает. - person Ali; 04.10.2012
comment
как насчет didAddAnnotationViews метода, который у меня есть? где я должен использовать ваш метод? - person Ali; 04.10.2012
comment
эй, приятель, это очень просто, просто посмотрите, создадите ли вы массив с объектом CLLocationCoordinate2D, в котором хранятся два местоположения, и добавьте это в arrLocation, и вызовите этот метод в методе LocationUpdate или методе viewWillAppear.. просто попробуйте использовать его.. - person Paras Joshi; 04.10.2012
comment
также вызовите метод didAddAnnotationViews - person Paras Joshi; 04.10.2012
comment
но didAddAnnotationViews:(NSArray *)viewsas вы видите имеет NSArray. Я мог бы использовать его для моего текущего местоположения. (вы можете видеть в коде, которым я поделился в вопросе), но как насчет моего CLLocationCoordinate2D location? мне нужно создать свой собственный «arrLocation»? тогда каково использование параметра _NSArray? - person Ali; 04.10.2012
comment
Я просто пытаюсь использовать ваш код. У меня есть исключение: 2012-10-04 MapKitDemo[1802:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid Region <center:+0.00000000, +0.00000000 span:-360.00000000, -720.00000000>' *** - person Ali; 04.10.2012
comment
После вызова startUpdatingLocation обновление местоположения может занять несколько секунд, поэтому вы не можете попытаться получить его сразу после этого. Пока он не будет обновлен, местоположение содержит недопустимые значения, о чем вам сообщает ошибка. Вместо этого реализуйте метод делегата locationManager:didUpdateToLocation:fromLocation: и прочитайте там местоположение. Переместите весь код после startUpdatingLocation в этот метод - person Paras Joshi; 05.10.2012
comment
попробуйте центрировать карту, создайте метод и в этом методе напишите [locationManager stopUpdatingLocation]; и после вызова вышеуказанного метода bt проверьте, что наша пользовательская arrLocation не пуста, хорошо, приятель .. :) - person Paras Joshi; 05.10.2012
comment
Я не смог реализовать ваш подход, но, кстати, нашел решение. +1 за помощь. - person Ali; 08.10.2012

Вот как я мог бы это реализовать:

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for(id<MKAnnotation> annotation in mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;

    // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;

    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
person Ali    schedule 05.10.2012