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 *)viewsкакто виждате има 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