Pergunta

Estou procurando ajuda para concluir algum código na definição da região em um MKMAPView com base na anotação atual do local e em uma anotação que eu defini.

Quero calcular a distância entre os dois e definir o centro entre os dois e depois diminuir o zoom para que ambos estejam à vista. Parece funcionar bem no simulador para mim, mas infelizmente a coordenada do userlocation. é fixada no HQ da Apple. Quando testo em um dispositivo, estou vendo um comportamento estranho. Freqüentemente, ele zoom e define uma região adequada se as duas anotações estiverem um pouco horizontalmente na mesma latitude, mas se a distância vertical for maior, não estiver aumentando corretamente.

Eu usei o código encontrado aqui, e editado um pouco para atender às minhas necessidades:

CLLocationCoordinate2D southWest = mapView.userLocation.coordinate;
CLLocationCoordinate2D northEast = southWest;

southWest.latitude = MIN(southWest.latitude, annotation.coordinate.latitude);
southWest.longitude = MIN(southWest.longitude, annotation.coordinate.longitude);

northEast.latitude = MAX(northEast.latitude, annotation.coordinate.latitude);
northEast.longitude = MAX(northEast.longitude, annotation.coordinate.longitude);

CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:southWest.latitude longitude:southWest.longitude];
CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:northEast.latitude longitude:northEast.longitude];

// This is a diag distance (if you wanted tighter you could do NE-NW or NE-SE)
CLLocationDistance meters = [locSouthWest distanceFromLocation:locNorthEast];

MKCoordinateRegion region;
region.center.latitude = (southWest.latitude + northEast.latitude) / 2.0;
region.center.longitude = (southWest.longitude + northEast.longitude) / 2.0;
region.span.latitudeDelta = meters / 111319.5;
region.span.longitudeDelta = 0.0;

MKCoordinateRegion savedRegion = [mapView regionThatFits:region];
[mapView setRegion:savedRegion animated:YES];

[locSouthWest release];
[locNorthEast release];

Uma coisa que me confundiu é que ele diz northEast = southWest...

Agradecemos antecipadamente a quem tem ajuda e entrada :)

Foi útil?

Solução

Esta postagem de blog pode fornecer a você a visão de necessidade

http://codisllc.com/blog/zoom-mkmapview-to-fit-annotações/

-(void)zoomToFitMapAnnotations:(MKMapView*)mapView
{
    if([mapView.annotations count] == 0)
        return;

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

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

    for(MapAnnotation* 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; // Add a little extra space on the sides

    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}

Outras dicas

Para o iOS7, a melhor maneira de fazer isso é:

//from API docs: 
//- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
[self.mapView showAnnotations:self.mapView.annotations animated:YES];

Para o meu projeto pessoal (antes do iOS7), simplesmente adicionei uma categoria na classe Mkmapview para encapsular a funcionalidade "área visível" para uma operação muito comum: configurando-o para poder ver todas as anotações atualmente carregadas na instância do MKMapView ( Isso inclui tantos pinos quanto você pode ter colocado, bem como a localização do usuário). O resultado foi o seguinte:

.h arquivo

#import <MapKit/MapKit.h>

@interface MKMapView (Extensions)

-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated;
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated;


@end

.m arquivo

#import "MKMapView+Extensions.h"

@implementation MKMapView (Extensions)

/**
 *  Changes the currently visible portion of the map to a region that best fits all the currently loadded annotations on the map, and it optionally animates the change.
 *
 *  @param animated is the change should be perfomed with an animation.
 */
-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated
{
    MKMapView * mapView = self;

    NSArray * annotations = mapView.annotations;

    [self ij_setVisibleRectToFitAnnotations:annotations animated:animated];

}


/**
 *  Changes the currently visible portion of the map to a region that best fits the provided annotations array, and it optionally animates the change.
    All elements from the array must conform to the <MKAnnotation> protocol in order to fetch the coordinates to compute the visible region of the map.
 *
 *  @param annotations an array of elements conforming to the <MKAnnotation> protocol, holding the locations for which the visible portion of the map will be set.
 *  @param animated    wether or not the change should be perfomed with an animation.
 */
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated
{
    MKMapView * mapView = self;

    MKMapRect r = MKMapRectNull;
    for (id<MKAnnotation> a in annotations) {
        ZAssert([a conformsToProtocol:@protocol(MKAnnotation)], @"ERROR: All elements of the array MUST conform to the MKAnnotation protocol. Element (%@) did not fulfill this requirement", a);
        MKMapPoint p = MKMapPointForCoordinate(a.coordinate);
        //MKMapRectUnion performs the union between 2 rects, returning a bigger rect containing both (or just one if the other is null). here we do it for rects without a size (points)
        r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0));
    }

    [mapView setVisibleMapRect:r animated:animated];

}

@end

Como você pode ver, adicionei 2 métodos até agora: um para definir a região visível do mapa para aquela que se encaixa em todas as anotações atualmente carregadas na instância do MKMapView e outro método para defini-lo em qualquer matriz de objetos. Então, para definir a região visível do MapView, o código seria tão simples como:

   //the mapView instance  
    [self.mapView ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:animated]; 

Espero que ajude =)

Não se assuste com as duas primeiras linhas, você pode ignorar o que está certo de = sinais, pois será substituído abaixo ...

Eu acho que a questão está aqui:

region.span.longitudeDelta = 0.0;

Versão Swift 4 de Robertibiris responda:

mapView.showAnnotations(mapView.annotations, animated: true)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top