geocoder iphone google-maps mkmapview user-input mkannotation

iphone - geocoder - ¿Cómo coloco un pin con MapKit?



geocoder swift (4)

Me gustaría permitir que el usuario de mi aplicación elija una ubicación en el mapa. El mapa nativo tiene una función de "soltar pin" donde puedes localizar algo soltando un pin. ¿Cómo puedo hacer esto en MapKit?


Hay varias formas de soltar un pin y no especifica la forma de hacerlo en su pregunta. La primera forma es hacerlo mediante programación, 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 te dirijas). Para iOS 4.0 y versiones posteriores, puede usar este fragmento de código para quitar un pin mediante programación:

// 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 desea poder soltar un pin, por ejemplo, al presionar prolongadamente el mapView real, puede hacerlo de la siguiente manera:

// 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 de código. Así es como se registran 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); }


También es posible que necesite establecer MapView Delegate.

[mkMapView setDelegate:self];

Luego 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; }


puede obtener la ubicación tocada por, jcesarmobile responda al obtener coordenadas marcadas con iphone mapkit y puede colocar el pin en cualquier lugar como se muestra a continuación.

// 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];


Debe crear un objeto que implemente el protocolo MKAnnotation y luego agregar ese objeto a MKMapView :

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

Cree una instancia de su objeto delegado y agréguelo 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 su vista de anotación, deberá implementar el método MKMapViewDelegate viewForAnnotation en su controlador de vista de mapa:

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

Si desea implementar la funcionalidad de arrastre de pines, puede leer sobre el manejo de eventos táctiles de anotación en la Biblioteca de referencia del sistema operativo Apple .

También puede consultar este artículo sobre la función de arrastrar y soltar con mapkit, que hace referencia a una biblioteca de muestra que funciona en GitHub . Puede obtener las coordenadas de la anotación arrastrada comprobando el miembro _coordinates en el objeto DDAnnotation .