2009-12-16 13 views
17

Me gustaría permitir que el usuario de mi aplicación elija una ubicación en el mapa. El mapa nativo tiene una característica de "colocar un alfiler" donde puedes encontrar algo al soltar un alfiler. ¿Cómo puedo hacer esto en MapKit?¿Cómo coloco un pin con MapKit?

+0

Si hay algo que puedo aclarar con mi respuesta. Por favor hagamelo saber. – RedBlueThing

+0

Cuando se escribió esto, hubo al menos dos buenas respuestas para elegir. Elige tu opción. – JugsteR

Respuesta

27

Es necesario crear un objeto que implementa la MKAnnotation protocolo y luego agregar ese objeto a la MKMapView:

@interface AnnotationDelegate : NSObject <MKAnnotation> { 
    CLLocationCoordinate2D coordinate; 
    NSString * title; 
    NSString * subtitle; 
} 

instancia su objeto delegado y agregarlo al mapa:

AnnotationDelegate * annotationDelegate = [[[AnnotationDelegate alloc] initWithCoordinate:coordinate andTitle:title andSubtitle:subt] autorelease]; 
[self._mapView addAnnotation:annotationDelegate]; 

El mapa accederá a la propiedad de coordenadas en su AnnotationDelegate para averiguar dónde colocar el pin en el mapa.

Si desea personalizar la vista de anotación que se necesita para implementar el MKMapViewDelegateviewForAnnotation método en el mapa Vista Controlador:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation 

Si desea implementar la funcionalidad pasador de arrastre que pueda lea sobre el manejo de eventos táctiles de anotación en el Apple OS Reference Library.

También puede consultar this article en arrastrar y soltar con mapkit que hace referencia a una biblioteca de ejemplos en funcionamiento en GitHub. Puede obtener las coordenadas de la anotación arrastrada marcando el _coordinates miembro en el objeto DDAnnotation.

+0

Hay una buena publicación en el blog y un código de muestra para arrastrar y soltar la anotación aquí: http://hollowout.blogspot.com/2009/07/mapkit-annotation-drag-and-drop-with.html – RedBlueThing

+0

La cosa es incluso si son capaces de arrastrar, ¿sería capaz de obtener la ubicación del pin después de que se hace arrastrando? – erotsppa

+0

He actualizado mi respuesta con un poco más de detalle sobre las cosas para arrastrar y soltar. – RedBlueThing

23

Hay varias maneras de soltar un pin, y no especifica en qué forma hacerlo en su pregunta. La primera forma es hacerlo programáticamente, para eso puedes usar lo que escribió RedBlueThing, excepto que realmente no necesitas una clase personalizada (dependiendo de la versión de iOS a la que estés apuntando). Para iOS 4.0 y posterior puede utilizar este fragmento a caer programación un pin:

// Create your coordinate 
CLLocationCoordinate2D myCoordinate = {2, 2}; 
//Create your annotation 
MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; 
// Set your annotation to point at your coordinate 
point.coordinate = myCoordinate; 
//If you want to clear other pins/annotations this is how to do it 
for (id annotation in self.mapView.annotations) { 
    [self.mapView removeAnnotation:annotation]; 
} 
//Drop pin on map 
[self.mapView addAnnotation:point]; 

Si usted quiere ser capaz de dejar caer un alfiler por ejemplo con una presión prolongada sobre la MAPview real, se puede hacer así:

// Create a gesture recognizer for long presses (for example in viewDidLoad) 
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; 
lpgr.minimumPressDuration = 0.5; //user needs to press for half a second. 
[self.mapView addGestureRecognizer:lpgr] 


- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer { 
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan) { 
     return; 
    } 
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView]; 
    CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView]; 
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; 
    point.coordinate = touchMapCoordinate; 
    for (id annotation in self.mapView.annotations) { 
     [self.mapView removeAnnotation:annotation]; 
    } 
    [self.mapView addAnnotation:point]; 
} 

Si desea enumerar todas las anotaciones, solo use el código en ambos fragmentos. Así es como registra las posiciones para todas las anotaciones:

for (id annotation in self.mapView.annotations) { 
    NSLog(@"lon: %f, lat %f", ((MKPointAnnotation*)annotation).coordinate.longitude,((MKPointAnnotation*)annotation).coordinate.latitude); 
} 
+0

esta pregunta respondió lo que preguntó @erotsppa – JProgrammer

2

Es posible que también tenga que configurar Delegado de MapView.

[mkMapView setDelegate:self]; 

A continuación, llame a su delegado, viewForAnnotation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{ 
    MKPinAnnotationView *pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation 
                    reuseIdentifier:@"current"]; 
    pinAnnotationView.animatesDrop = YES; 
    pinAnnotationView.pinColor = MKPinAnnotationColorRed; 
    return pinAnnotationView; 
} 
8

se puede obtener la ubicación tocada por, jcesarmobile respuesta en conseguir unos golpecitos coordinates with iphone mapkit y se puede caer un alfiler en cualquier lugar como bramido

// Define pin location 
CLLocationCoordinate2D pinlocation; 
pinlocation.latitude = 51.3883454 ;//set latitude of selected coordinate ; 
pinlocation.longitude = 1.4368011 ;//set longitude of selected coordinate; 

// Create Annotation point 
MKPointAnnotation *Pin = [[MKPointAnnotation alloc]init]; 
Pin.coordinate = pinlocation; 
Pin.title = @"Annotation Title"; 
Pin.subtitle = @"Annotation Subtitle"; 

// add annotation to mapview 
[mapView addAnnotation:Pin]; 
Cuestiones relacionadas