Selected map pins show the same coordinate - ios

I am trying get the coordinate of each pin I select on my map. Pins are the local search results that users search on the map. I have an issue that every pin I select it give me the same value. Can anyone help me with this please? Thanks in advance.
- (IBAction)searchAction:(id)sender {
[sender resignFirstResponder];
[self.mapView removeAnnotations:[self.mapView annotations]];
[self performSearch]; }
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKPinAnnotationView *mypin = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:#"current"];
//mypin.pinColor = MKPinAnnotationColorPurple;
mypin.backgroundColor = [UIColor clearColor];
UIButton *goToDetail = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
mypin.rightCalloutAccessoryView = goToDetail;
mypin.draggable = NO;
mypin.highlighted = YES;
mypin.animatesDrop = TRUE;
mypin.canShowCallout = YES;
return mypin;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
MKPointAnnotation *annotation = view.annotation;
self.tappedCoord = annotation.coordinate;
// Longs are the same for every pin I select
NSLog(#"%f", [[view annotation] coordinate].longitude);
}
- (void)performSearch {
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = _searchText.text;
request.region = _mapView.region;
self.matchingItems = [[NSMutableArray alloc] init];
MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
[self.matchingItems addObject:item];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
annotation.subtitle = [NSString stringWithFormat:#"%#, %# %#",
item.placemark.addressDictionary[#"Street"],
item.placemark.addressDictionary[#"State"],
item.placemark.addressDictionary[#"ZIP"]];
//NSLog(#"%#", item.placemark.addressDictionary);
[_mapView addAnnotation:annotation];
}
}];
}

Related

Obj-C - Custom Map Annotation Callout View from XIB

I'm trying to have a custom view/XIB display when an annotation on my MapView is tapped. That said, I've found various answers to this question for swift - but none for objective C.
Currently, I'm able to display custom annotations with the following code:
ViewController.m
-(void)viewDidLoad {
NSMutableDictionary *viewParamsFriend = [NSMutableDictionary new];
[viewParamsFriend setValue:#"accepted_friends" forKey:#"view_name"];
[DIOSView viewGet:viewParamsFriend success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.friendData = [responseObject mutableCopy];
int index = 0;
for (NSMutableDictionary *multiplelocationsFriend in self.friendData) {
NSString *location = multiplelocationsFriend[#"address2"];
NSString *userNames = multiplelocationsFriend[#"node_title"];
NSString *userBio = multiplelocationsFriend[#"body"];
CLGeocoder *geocoderFriend = [[CLGeocoder alloc] init];
[geocoderFriend geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKCoordinateRegion region = self.friendsMapView.region;
region.span.longitudeDelta /= 150.0;
region.span.latitudeDelta /= 150.0;
PointAnnotation *point = [[PointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = userNames;
point.subtitle = userBio;
point.index = index; // Store index here.
[self.friendsMapView addAnnotation:point];
}
}
];
index = index + 1;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
MKAnnotationView *pinView = (MKAnnotationView*)[self.friendsMapView dequeueReusableAnnotationViewWithIdentifier:#"AnnotationIdentifier"];
if (!pinView)
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"AnnotationIdentifier"];
pinView.image = [UIImage imageNamed:#"mapann3.png"];
} else {
pinView.annotation = annotation;
}
pinView.canShowCallout = YES;
pinView.calloutOffset = CGPointMake(0, 0);
UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mapann3.png"]];
pinView.leftCalloutAccessoryView = iconView;
return pinView;
}
return nil;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(calloutTappedTwo:)];
[view addGestureRecognizer:tapGesture2];
}
-(void)calloutTappedTwo:(UITapGestureRecognizer *) sender
{
MKAnnotationView *view = (MKAnnotationView*)sender.view;
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:#"OtherUserViewController"];
NSMutableDictionary *dictionary = self.friendData[selectedPoint.index];
yourViewController.frienduserData = dictionary;
[self.navigationController pushViewController:yourViewController animated:YES];
}
}
That said, if I want a custom XIB I've created to appear as the callout when each annotation is tapped, where/how should I call this?

How to add Tap gesture on MKPointAnnotation to show another view with data?

I have a an array of latitude and longitude and using for loop am displaying the MKPointAnnotation on the map. I want to show a view as a popup with data when the specific MKPointAnnotation is tapped.
Here is my code -
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 10000, 10000);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
[_locationManager stopUpdatingLocation];
NSArray *set = [[NSArray alloc] init];
for (int i = 0; i < _json.count; i++) {
_name = [_json[i] valueForKey:#"name"];
_class = [_json[i] valueForKey:#"class"];
set = [_json[i] valueForKey:#"set"];
if (setFreeHour.count != 0) {
for (int j=0;j<set.count;j++) {
NSDictionary *dict = [[NSDictionary alloc] init];
dict = set[j];
_lat = dict[#"latitude"];
_longi = dict[#"longitude"];
CLLocationCoordinate2D coordinate;
coordinate.latitude = [_lat doubleValue];
coordinate.longitude = [_longi doubleValue];
// Add an annotation
MKPointAnnotation *point1 = [[MKPointAnnotation alloc] init];
point1.coordinate = CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude);
point1.title = _name;
point1.subtitle = _class;
[self.mapView addAnnotation:point1];
}
}
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:#"CustomPinAnnotationView"];
if (!pinView) {
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"CustomPinAnnotationView"];
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:#"annotation"];
pinView.calloutOffset = CGPointMake(0, 0);
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showDetails)];
[pinView addGestureRecognizer:tap];
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
- (void)showDetails{
self.popup.hidden = NO;
}
//PS: popup is a view that contains labels. I want to pass data from MKPointAnnotation to the view
Why don't you use mapView(_:didSelect:) method instead of UITapGestureRecognizer?
(void)mapView:(MKMapView *)mapview didSelectAnnotationView:(MKAnnotationView *)view {
// 1. get data from view(MKAnnotationView)
// 2. pass data to another view
}
https://developer.apple.com/documentation/mapkit/mkmapviewdelegate/1452393-mapview

How to add an UIButton to placemark? ios objective c

How do I add a button to my placemarks and then get it to push onto a view controller?
- (void)viewDidLoad
{
[super viewDidLoad];
// Set "More" logo in navigation bar
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Navigation"]];
appDelegate=[[UIApplication sharedApplication] delegate];
// Set longatude and latitude to tyne and wear
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(54.995184, -1.566699);
// Set span to cover area
MKCoordinateSpan span = MKCoordinateSpanMake(0.5, 0.5);
// Set region
MKCoordinateRegion regionToDisplay = MKCoordinateRegionMake(center, span);
[self.nearbyMapView setRegion: regionToDisplay];
for (int i = 0; i < [[appDelegate offersFeeds] count]; i++)
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
NSString *plotAddress = [[[appDelegate offersFeeds] objectAtIndex:i] valueForKey:#"addressline"];
NSString *plotTitle = [[[appDelegate offersFeeds] objectAtIndex:i] valueForKey:#"title"];
[geocoder geocodeAddressString:plotAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc]initWithPlacemark:topResult];
// Set title
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = placemark.location.coordinate;
pa.title = plotTitle;
// Add placemark to map
[self.nearbyMapView addAnnotation:pa];
}
}];
}
}
I've had a look at MKAnotationView but struggling to understand how to get this working with CLPlacemark.
Add this before you add mapview to self.view
-(void)viewDidLoad
{
MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
annotation.coordinate = yourCoordinate;
annotation.title = #"Title";
annotation.subtitle = #"SubTitle";
[mapView1 addAnnotation:annotation];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *pinView = nil;
static NSString *defaultPinID = #"identifier";
pinView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID];
annotationView.enabled = YES;
pinView.canShowCallout = YES;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//Accessoryview for the annotation view in ios.
pinView.rightCalloutAccessoryView = btn;
}
else
{
pinView.annotation = annotation;
}
pinView.annotation = annotation;
return pinView;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
//Put your button stuff here...
}
I hope it is useful to you

mapView and UITable detail

trying to pass my annotation's data (name, address, phone #, url, description, etc) to a DetailViewController with a table. stuck----please read the code. the data isnt passed with calloutAccessoryTapped. Help?
- (IBAction)gasButton:(id)sender {
[self.mapView removeAnnotations:self.mapView.annotations];
self.localSearchRequest = [[MKLocalSearchRequest alloc] init];
self.localSearchRequest.region = self.mapView.region;
self.localSearchRequest.naturalLanguageQuery = #"gas station";
self.localSearch = [[MKLocalSearch alloc] initWithRequest:self.localSearchRequest];
[self.localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if(error){
NSLog(#"localSearch startWithCompletionHandlerFailed! Error: %#", error);
return;
} else {
for(mapItem in response.mapItems){
MKPointAnnotation *zip = [[MKPointAnnotation alloc] init ];
zip.coordinate = mapItem.placemark.location.coordinate;
zip.title = mapItem.name;
self.mapView.delegate = self;
[self.mapView addAnnotation: zip];
[self.mapView selectAnnotation:zip animated:YES];
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow];
NSLog(#"%# - 1", mapItem.name);
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:zip.coordinate.latitude longitude:zip.coordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSString *dist = [[NSString alloc] initWithFormat:#"%.2f miles", distance * 0.000621371192];
zip.subtitle = dist;
}
}
}];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"MYVC"];
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
else if ([annotation isKindOfClass: [MKPointAnnotation class] ])
{
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annotationView.enabled = YES;
annotationView.animatesDrop = YES;
annotationView.pinColor = MKPinAnnotationColorGreen;
annotationView.canShowCallout = YES;
NSLog(#"%# - 2", mapItem.name);
return annotationView;
}
return nil;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%# - tapped", mapItem.name);
//STUCK HERE - mapItem.name is (null)
}
mapItem exists in the for loop of your gasButton function, no where else as far as I can see. You've created an annotation (zip) and added it to your map. In viewForAnnotation you are given that annotation as a parameter and asked to make an annotationView from it. In calloutAccessoryControlTapped you are given an annotationView and told it has been tapped. You need to follow the chain back to your data. From the annotationView get the annotation and from the annotation get your name.
MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%# - tapped", view.annotation.title);
}

iOS distinguish between which callout accessory is tapped

In my map annotations, I have a UIButton as each accessory view in the callouts. In the - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control method, how do I figure out which accessory view was touched to handle each the events? Here's my code:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
UIButton *calloutButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
UIButton *directionsButton = [UIButton buttonWithType:UIButtonTypeCustom];
directionsButton.frame = CGRectMake(0, 0, 23, 23);
[directionsButton setBackgroundImage:[UIImage imageNamed:#"directions.png"] forState:UIControlStateNormal];
MyPin.leftCalloutAccessoryView = directionsButton;
MyPin.rightCalloutAccessoryView = calloutButton;
MyPin.draggable = NO;
MyPin.highlighted = NO;
MyPin.animatesDrop= YES;
MyPin.canShowCallout = YES;
MyPin.pinColor = MKPinAnnotationColorRed;
return MyPin;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
Annotation *ann = view.annotation;
if ([control tag] == 1) {
CLLocationCoordinate2D currentCoords = {ann.coordinate.latitude, ann.coordinate.longitude};
MKPlacemark *place = [[MKPlacemark alloc] initWithCoordinate: currentCoords addressDictionary:nil];
MKMapItem *destination = [[MKMapItem alloc] initWithPlacemark: place];
destination.name = ann.title;
destination.url = [NSURL URLWithString:#"http://www.wccca.com/PITS"];
NSArray *items = [[NSArray alloc] initWithObjects: destination, nil];
NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:
MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsDirectionsModeKey, nil];
[MKMapItem openMapsWithItems: items launchOptions: options];
}
if ([control tag] == 2) {
MKCoordinateRegion region;
region.center.latitude = ann.coordinate.latitude;
region.center.longitude = ann.coordinate.longitude;
region.span.latitudeDelta = 0.02;
region.span.longitudeDelta = 0.02;
[self.mapView setRegion:region animated:YES];
}
}
Rather than setting and using tags, you could just check if control is the left or right accessory view:
if (control == view.leftCalloutAccessoryView) {
//handle left control tap...
}
else
if (control == view.rightCalloutAccessoryView) {
//handle right control tap...
}

Resources