When I am searching a place it drops a pin mapView - ios

I am stuck with a problem on the mapView. I am really sorry to ask this question but I have searched for almost one day to look into this issue but I don't find a solution to fix it.
#interface MapViewController ()<CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, CheckInDelegate, NotificationsViewControllerDelegate, ReportVCDelegate, TutorialViewControllerDelegate> {
CLLocationManager *locationManager;
NSTimer *refreshTimer;
int rangeValue;
CheckInViewController *checkInVC;
TutorialViewController *tutorialVC1;
TutorialViewController *tutorialVC2;
UIImageView *imgAvatar;
NSArray *markers;
}
#property (weak, nonatomic) IBOutlet UIView *viewSearch;
#property (weak, nonatomic) IBOutlet RateView *viewRate;
#property (weak, nonatomic) IBOutlet UIView *viewBottom;
#property (weak, nonatomic) IBOutlet UILabel *lblUsername;
#property (weak, nonatomic) IBOutlet UITextField *txtSearch;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *btnNotifications;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;
#property (weak, nonatomic) IBOutlet UIButton *btnBottom;
#property (weak, nonatomic) IBOutlet HandsawayMapView *mapView;
#property (weak, nonatomic) IBOutlet UIView *mapViewContainer;
#property (strong, nonatomic) MKPlacemark *searchMarker;
#property (strong, nonatomic) MKUserLocation *myMarker;
#property (weak, nonatomic) MapToolbarViewController *mapToolbar;
#property (strong, atomic) NSArray *allMapMarkers;
#property (strong, nonatomic) NSNumber *aggressionIdToCenter;
#end
#implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// [[UserModel sharedModel] setUserHome:#(1)];
rangeValue = 300;
self.viewSearch.layer.masksToBounds = NO;
self.viewSearch.layer.shadowRadius = 0.5f;
self.viewSearch.layer.shadowColor = [UIColor blackColor].CGColor;
self.viewSearch.layer.shadowOffset = CGSizeMake(0.0f, 0.5f);
self.viewSearch.layer.shadowOpacity = 0.5f;
self.viewRate.starCount = 4;
self.viewRate.step = 1.0f;
self.viewRate.starNormalColor = UIColorFromRGB(0xD8D8D8);
self.viewRate.starFillColor = UIColorFromRGB(0xFF5B59);
self.viewRate.rating = 3.0f;
self.viewRate.starSize = 20.0f;
self.viewRate.padding = 8.0f;
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
locationManager.delegate = self;
[DbHelper saveActivationWithNumer:#(1)];
imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
}];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSNumber *agressionID = [[NSUserDefaults standardUserDefaults] valueForKey:#"aggression_id"];
if (agressionID && agressionID != 0)
{
self.aggressionIdToCenter = agressionID;
[[NSUserDefaults standardUserDefaults] setValue:0 forKey:#"aggression_id"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
if (self.aggressionIdToCenter != nil) {
[self centerOnAggressionWithId:self.aggressionIdToCenter];
self.aggressionIdToCenter = nil;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[locationManager stopUpdatingLocation];
didSetLocation = NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIView*)locationPin {
User *user = [DbHelper getCurrentUser];
UIImage *pin = [UIImage imageNamed:#"marker-person"];
if([user.isCurrent boolValue]) {
pin = [UIImage imageNamed:#"my-pin"];
}
UIImageView *pinImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 39, 48)];
[pinImageView setImage:pin];
UIView *markerContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39, 48)];
[markerContainer addSubview:pinImageView];
imgAvatar = [[UIImageView alloc] initWithFrame:CGRectMake(4.5, 4.5, 30, 30)];
[imgAvatar setContentMode:UIViewContentModeScaleAspectFill];
imgAvatar.layer.cornerRadius = 15;
imgAvatar.clipsToBounds = YES;
[markerContainer addSubview:imgAvatar];
if([user.isPictureHidden boolValue]) {
[imgAvatar setImage:[user avatarPlaceholder]];
}
else {
[imgAvatar setImageWithURL:[NSURL URLWithString:user.pictureURL] placeholderImage:[user avatarPlaceholder]];
}
[pinImageView setBackgroundColor:[UIColor clearColor]];
[imgAvatar setBackgroundColor:[UIColor clearColor]];
[markerContainer setBackgroundColor:[UIColor clearColor]];
return markerContainer;
}
- (void)ckeckUserImage
{
User *user = [DbHelper getCurrentUser];
if([user.isPictureHidden boolValue]) {
[imgAvatar setImage:[user avatarPlaceholder]];
}
else {
[imgAvatar setImageWithURL:[NSURL URLWithString:user.pictureURL] placeholderImage:[user avatarPlaceholder]];
}
if (self.mapToolbar.currentUser)
{
[self.mapToolbar setCurrentUser];
}
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:#"PresentInfo"]) {
self.mapToolbar = segue.destinationViewController;
self.mapToolbar.height = self.bottomHeight;
self.mapToolbar.masterVC = self;
} else if ([segue.identifier isEqualToString:#"NotificationsSegue"] && [segue.destinationViewController isKindOfClass:[NotificationsViewController class]]) {
NotificationsViewController *destination = (NotificationsViewController *)segue.destinationViewController;
destination.delegate = self;
}
else if([segue.identifier isEqualToString:#"ActionSheetMap"]) {
self.VCactionSheetMap = segue.destinationViewController;
self.VCactionSheetMap.delegate = self.mapToolbar;
} else if ([segue.identifier isEqualToString:#"mapToReport"]) {
self.reportVC = (ReportVC *)segue.destinationViewController;
self.reportVC.delegate = self;
}
}
- (IBAction)onMenu:(id)sender {
[self.frostedViewController presentMenuViewController];
}
-(IBAction)onLocate:(id)sender {
self.txtSearch.text = #"";
[self.mapView removeAnnotation:self.searchMarker];
self.searchMarker = nil;
didSetLocation = NO;
}
- (IBAction)onCheckIn:(id)sender {
if([[NSUserDefaults standardUserDefaults] valueForKey:#"tutorials2"]) {
self.btnCheckin.hidden = YES;
checkInVC = [self.storyboard instantiateViewControllerWithIdentifier:#"NewCheckin"];
checkInVC.delegate = self;
checkInVC.model = [[CheckInModel alloc] init];
if(_searchMarker != nil) {
checkInVC.model.longitude = (double) _searchMarker.coordinate.longitude;
checkInVC.model.latitude = (double) _searchMarker.coordinate.latitude;
}
else {
checkInVC.model.longitude = (double) locationManager.location.coordinate.longitude;
checkInVC.model.latitude = (double) locationManager.location.coordinate.latitude;
}
if([sender isKindOfClass:[NSNumber class]]) {
checkInVC.agressionId = sender;
}
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:checkInVC.view];
}
else {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if(![[NSUserDefaults standardUserDefaults] valueForKey:#"tutorials2"]) {
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self.btnCheckin setAdjustsImageWhenHighlighted:NO];
[self.btnCheckin setUserInteractionEnabled:NO];
UIStoryboard *tutorials = [UIStoryboard storyboardWithName:#"Tutorial" bundle:nil];
tutorialVC2 = (TutorialViewController *)[tutorials instantiateViewControllerWithIdentifier:[NSString stringWithFormat:#"Tutorial%ld", (long)2]];
tutorialVC2.delegate = self;
[[tutorialVC2 view] setFrame:self.view.bounds];
[self.view insertSubview:[tutorialVC2 view] belowSubview:self.btnCheckin];
[[NSUserDefaults standardUserDefaults] setValue:#YES forKey:#"tutorials2"];
}
});
}
}
- (IBAction)onNotifications:(id)sender {
if([[NSUserDefaults standardUserDefaults] valueForKey:#"tutorials1"]) {
[self performSegueWithIdentifier:#"NotificationsSegue" sender:nil];
}
else {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if(![[NSUserDefaults standardUserDefaults] valueForKey:#"tutorials1"]) {
[self.navigationController setNavigationBarHidden:YES animated:YES];
UIStoryboard *tutorials = [UIStoryboard storyboardWithName:#"Tutorial" bundle:nil];
tutorialVC1 = (TutorialViewController *)[tutorials instantiateViewControllerWithIdentifier:[NSString stringWithFormat:#"Tutorial%ld", (long)1]];
tutorialVC1.delegate = self;
[[tutorialVC1 view] setFrame:self.view.bounds];
[self.view addSubview:[tutorialVC1 view]];
[[NSUserDefaults standardUserDefaults] setValue:#YES forKey:#"tutorials1"];
}
});
});
}
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
[manager startUpdatingLocation];
}
BOOL didSetLocation;
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations {
if(locations.count > 0 ) {
CLLocation *aUserLocation = locations[0];
self.myMarker.coordinate = aUserLocation.coordinate;
// if(_myMarker == nil) {
// GMSMarker *marker = [[GMSMarker alloc] init];
// marker.iconView = [[DbHelper getCurrentUser] locationPin];
// marker.map = mapView_;
// _myMarker = marker;
// }
// _myMarker.position = aUserLocation.coordinate;
if(!didSetLocation) {
didSetLocation = YES;
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01557113906538632;
span.longitudeDelta = 0.02284631241712987;
CLLocationCoordinate2D location;
location.latitude = aUserLocation.coordinate.latitude;
location.longitude = aUserLocation.coordinate.longitude;
region.span = span;
region.center = location;
[self.mapView setRegion:region animated:YES];
// [APICLIENT locateUserWithCoordinates:location
// completion:^(NSDictionary *result) {
//
// } error:^{
//
// }];
}
}
}
#pragma mark - Bottom bar
BOOL isBottomBarShown = YES;
}
#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
// NSLog(#"longitured : %#, lattitude: %#", #(mapView.region.span.longitudeDelta), #(mapView.region.span.latitudeDelta));
[self hideBottomView];
[refreshTimer invalidate];
refreshTimer = [NSTimer scheduledTimerWithTimeInterval:0.8
target:self
selector:#selector(refreshMapMarkersWithCoordinates:)
userInfo:#{#"longitude" : #(mapView.region.center.longitude), #"latitude" : #(mapView.region.center.latitude), #"range" : #(rangeValue)}
repeats:NO];
}
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if(![annotation isKindOfClass:[MKPlacemark class]]) {
MKAnnotationView * annotationView = [MKAnnotationView new];
if([annotation isKindOfClass:[MKUserLocation class]]) {
UIView *userView = [self locationPin];
[annotationView setFrame:userView.frame];
[annotationView addSubview:userView];
self.myMarker = annotation;
[self.mapView sendSubviewToBack:annotationView];
}
else {
annotationView.annotation = annotation;
Marker *dbmarker = ((MarkerAnnotation*)annotation).userData;
if(dbmarker.agression != nil) {
[annotationView setImage:[dbmarker markerImage]];
[self.mapView bringSubviewToFront:annotationView];
}
else if(dbmarker.user != nil) {
UIView *userView = [dbmarker userMarkerView];
[annotationView setFrame:userView.frame];
[annotationView addSubview:userView];
[self.mapView bringSubviewToFront:annotationView];
}
}
return annotationView;
}
return nil;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
if(view.annotation != self.searchMarker && view.annotation != self.myMarker) {
if([view.annotation isKindOfClass:[MKUserLocation class]]) {
}
else {
[self selectMarker:((MarkerAnnotation*)view.annotation).userData];
}
}
else
{
if (view.annotation == self.myMarker)
{
[self.mapToolbar setCurrentUser];
}
[self showBottomView];
}
}
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
if(view.annotation != self.searchMarker && view.annotation != self.myMarker) {
if([view.annotation isKindOfClass:[MKUserLocation class]]) {
}
else {
[self hideBottomView];
}
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
[APICLIENT locateUserWithCoordinates:userLocation.location.coordinate
completion:^(NSDictionary *result) {
} error:^{
}];
}
#pragma mark - GMSMap delegate
//- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
// [self selectMarker:marker];
// return YES;
//}
- (void)selectMarker:(Marker *)marker {
Marker *dbMarker = marker;
if(dbMarker.agression != nil) {
[APICLIENT getAgressionWithId:dbMarker.agression.webID
completion:^(Marker *newmarker) {
[APICLIENT getUserById:[newmarker.user.webID stringValue]
completion:^(User *result) {
self.mapToolbar.marker = newmarker;
//[self showBottomView];
} error:^{
}];
} error:^{
}];
}
else {
[APICLIENT getUserById:[dbMarker.user.webID stringValue]
completion:^(User *result) {
self.mapToolbar.marker = dbMarker;
[self showBottomView];
} error:^{
}];
}
}
-(void)reloadMarkers {
[APICLIENT getMapMarkersAroundMeWithCoordinates:self.mapView.region.center
range:#(rangeValue)
completion:^(NSArray *result) {
[self updateDistance];
NSArray *oldAnnotations = [self.mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF.class == %#", [MarkerAnnotation class]]];
oldAnnotations = [oldAnnotations valueForKey:#"userData"];
markers = [Marker MR_findAllWithPredicate:[NSPredicate predicateWithFormat:#"NOT (SELF IN %#)", oldAnnotations]];
//[self.mapView removeAnnotations:self.mapView.annotations];
NSMutableArray *allMapMarkersMutable = [[NSMutableArray alloc] init];
for(Marker *dbmarker in markers) {
MarkerAnnotation *marker = [[MarkerAnnotation alloc] init];
marker.coordinate = CLLocationCoordinate2DMake([dbmarker.latitude doubleValue], [dbmarker.longitude doubleValue]);
marker.userData = dbmarker;
[self.mapView addAnnotation:marker];
[allMapMarkersMutable addObject:marker];
}
self.allMapMarkers = [[allMapMarkersMutable copy] arrayByAddingObjectsFromArray:oldAnnotations];
if(_searchMarker != nil && ![self.mapView.annotations containsObject:_searchMarker]) {
[self.mapView addAnnotation:_searchMarker];
}
if(self.aggressionIdToCenter != nil) {
[self centerOnAggressionWithId:self.aggressionIdToCenter];
self.aggressionIdToCenter = nil;
}
} error:^{
}];
/*NSArray *oldAnnotations = [self.mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF.class == %#", [MarkerAnnotation class]]];
oldAnnotations = [oldAnnotations valueForKey:#"userData"];
markers = [Marker MR_findAllWithPredicate:[NSPredicate predicateWithFormat:#"NOT (SELF IN %#)", oldAnnotations]];
// [self.mapView removeAnnotations:self.mapView.annotations];
NSMutableArray *allMapMarkersMutable = [[NSMutableArray alloc] init];
for(Marker *dbmarker in markers) {
MarkerAnnotation *marker = [[MarkerAnnotation alloc] init];
marker.coordinate = CLLocationCoordinate2DMake([dbmarker.latitude doubleValue], [dbmarker.longitude doubleValue]);
marker.userData = dbmarker;
[self.mapView addAnnotation:marker];
[allMapMarkersMutable addObject:marker];
}
self.allMapMarkers = [[allMapMarkersMutable copy] arrayByAddingObjectsFromArray:oldAnnotations];
if(_searchMarker != nil && ![self.mapView.annotations containsObject:_searchMarker]) {
[self.mapView addAnnotation:_searchMarker];
}
if(self.aggressionIdToCenter != nil) {
[self centerOnAggressionWithId:self.aggressionIdToCenter];
self.aggressionIdToCenter = nil;
}*/
}
//-(void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
// [self hideBottomView];
//}
#pragma mark - UITextFieldDelegate and place search
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self.view endEditing:YES];
MKCoordinateRegion newRegion;
newRegion.center.latitude = locationManager.location.coordinate.latitude;
newRegion.center.longitude = locationManager.location.coordinate.longitude;
// Setup the area spanned by the map region:
// We use the delta values to indicate the desired zoom level of the map,
// (smaller delta values corresponding to a higher zoom level).
// The numbers used here correspond to a roughly 8 mi
// diameter area.
//
newRegion.span.latitudeDelta = 0.112872;
newRegion.span.longitudeDelta = 0.109863;
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = textField.text;
request.region = newRegion;
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
MKLocalSearchCompletionHandler completionHandler = ^(MKLocalSearchResponse *response, NSError *error) {
if (error != nil) {
// NSString *errorStr = [[error userInfo] valueForKey:NSLocalizedDescriptionKey];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not find places"
// message:errorStr
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
} else {
NSArray<MKMapItem *> *mapItems = [response mapItems];
if(mapItems.count > 0) {
MKCoordinateRegion boundingRegion = response.boundingRegion;
MKMapItem *item = mapItems[0];
self.searchMarker = item.placemark;
[self.mapView addAnnotation:item.placemark];
[self.mapView setRegion:boundingRegion animated:YES];
}
}
};
[localSearch startWithCompletionHandler:completionHandler];
double radians(double degrees) {
return degrees * M_PI / 180.0;
}
double degrees(double radians) {
return radians * 180.0 / M_PI;
}
const CLLocationDegrees kLatLonEarthRadius = 6371.0;
CLLocationCoordinate2D LatLonDestPoint(CLLocationCoordinate2D origin, double bearing, CLLocationDistance distance) {
double brng = radians(bearing);
double lat1 = radians(origin.latitude);
double lon1 = radians(origin.longitude);
CLLocationDegrees lat2 = asin(sin(lat1) * cos(distance / kLatLonEarthRadius) +
cos(lat1) * sin(distance / kLatLonEarthRadius) * cos(brng));
CLLocationDegrees lon2 = lon1 + atan2(sin(brng) * sinf(distance / kLatLonEarthRadius) * cos(lat1),
cosf(distance / kLatLonEarthRadius) - sin(lat1) * sin(lat2));
lon2 = fmod(lon2 + M_PI, 2.0 * M_PI) - M_PI;
CLLocationCoordinate2D coordinate;
if (! (isnan(lat2) || isnan(lon2))) {
coordinate.latitude = degrees(lat2);
coordinate.longitude = degrees(lon2);
}
return coordinate;
}
#pragma mark - CheckInDelegate
- (void)willRemoveCheckinView {
[[UIApplication sharedApplication] setStatusBarHidden:NO
withAnimation:UIStatusBarAnimationSlide];
[self.navigationController setNavigationBarHidden:NO
animated:YES];
}

The problem is you are adding marker in MKLocalSearchCompletionHandler, so remove below line from MKLocalSearchCompletionHandler will solved your issue.
[self.mapView addAnnotation:item.placemark];

You can remove all annotation pins from MKMapView by using following code
for (int i =0; i < [_mapView.annotations count]; i++) {
if ([[_mapView.annotations objectAtIndex:i] isKindOfClass:[YOURANNOTATIONCLASS class]]) {
[_mapView removeAnnotation:[_mapView.annotations objectAtIndex:i]];
}
}

If you want to remove Annotation while search then remove bellow code in textFieldShouldReturn method.
Find method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
}
Then Comment or Remove bellow code
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = textField.text;
request.region = newRegion;
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
MKLocalSearchCompletionHandler completionHandler = ^(MKLocalSearchResponse *response, NSError *error) {
if (error != nil) {
// NSString *errorStr = [[error userInfo] valueForKey:NSLocalizedDescriptionKey];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not find places"
// message:errorStr
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
} else {
NSArray<MKMapItem *> *mapItems = [response mapItems];
if(mapItems.count > 0) {
MKCoordinateRegion boundingRegion = response.boundingRegion;
MKMapItem *item = mapItems[0];
self.searchMarker = item.placemark;
[self.mapView addAnnotation:item.placemark];
[self.mapView setRegion:boundingRegion animated:YES];
}
}
};
Hope it will help you

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?

Map Zooms Back Out after releasing on Zoom-in

I have MapView that shows two points on a map with a route. When I zoom into the map, after I release, the map zooms back out.
I have zoomEnabled and scrollEnabled all set to yes in Code and on the InterfaceBuilder
#interface MapViewController () <UIApplicationDelegate, MKMapViewDelegate,CLLocationManagerDelegate> {
CLLocationManager * locationManager;
CLPlacemark * pmDesination;
CLLocation * currentLocation;
MyAnnotation * destinationAnn;
MKPolyline *_routeOverlay;
MKRoute *_currentRoute;
}
#end
#implementation MapViewController
const static int TYPE_STATUS_PICKUP = 0;
const static int TYPE_STATUS_DROPOFF = 1;
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self stopLocationServices];
}
- (void) viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
self.mapView.zoomEnabled = YES;
self.mapView.scrollEnabled = YES;
[self startLocationServices];
//Show points on map
[self addressSearch:self.pickupLocation type:TYPE_STATUS_PICKUP];
[self addressSearch:self.dropoffLocation type:TYPE_STATUS_DROPOFF];
}
- (void) mapViewDidFinishLoadingMap:(MKMapView *)mapView {
[self showRoute];
NSMutableArray * pins = [[NSMutableArray alloc] init];
if (destinationAnn != nil) {
[pins addObject:destinationAnn];
}
if ([self getCurrentLocationAnnotation] != nil) {
[pins addObject:[self getCurrentLocationAnnotation]];
}
if (pins.count > 0) {
[_mapView showAnnotations:pins animated:YES];
}
}
#pragma mapping methods
- (void) addressSearch:(NSMutableDictionary *)pinLocation type:(int)type {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:pinLocation[#"address"] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error) {
//ERROR LOOKING UP ADDRESS
} else {
CLPlacemark * pm = [placemarks lastObject];
location.latitude = pm.location.coordinate.latitude;
location.longitude = pm.location.coordinate.longitude;
[ann setCoordinate:location];
ann.title = [pinLocation objectForKey:#"title"];
ann.subtitle = [pinLocation objectForKey:#"address"];
if (type == _toLocation) {
destinationAnn = ann;
}
[self.mapView addAnnotation:ann];
}
}];
}
#pragma mark - SHOW ROUTE
- (void) showRoute {
MKDirectionsRequest *directionsRequest = [MKDirectionsRequest new];
MKMapItem *source = [MKMapItem mapItemForCurrentLocation];
// Make the destination
CLLocationCoordinate2D destinationCoords = CLLocationCoordinate2DMake(destinationAnn.coordinate.latitude, destinationAnn.coordinate.longitude);
MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:destinationCoords addressDictionary:nil];
MKMapItem *destination = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
// Set the source and destination on the request
[directionsRequest setSource:source];
[directionsRequest setDestination:destination];
MKDirections *directions = [[MKDirections alloc] initWithRequest:directionsRequest];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(#"There was an error getting your directions: %#", error.localizedDescription);
return;
}
_currentRoute = [response.routes firstObject];
[self plotRouteOnMap:_currentRoute];
}];
}
- (void)plotRouteOnMap:(MKRoute *)route
{
if(_routeOverlay) {
[self.mapView removeOverlay:_routeOverlay];
}
// Update the ivar
_routeOverlay = route.polyline;
// Add it to the map
[self.mapView addOverlay:_routeOverlay];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
renderer.strokeColor = _toLocation ? [UIColor orangeColor] : [UIColor greenColor];
renderer.lineWidth = 4.0;
return renderer;
}
// DELGATE THAT RUNS TO SHOW CURRENT USER LOCATION
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(nonnull NSError *)error {
NSLog(#"Location Services Error: %#", [error description]);
[[LoggingManager sharedReporting] addReportToLog:[NSString stringWithFormat:#"Mapping: locationManager:didFailWithError: %#",[error description] ]];
}
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations: (NSArray *)locations {
currentLocation = [locations lastObject];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
currentLocation = newLocation;
}
#pragma mark - GET TO AND CURRENT POINTS
- (NSString*) getDestination {
NSDictionary * desDict = _toLocation ? self.dropoffLocation : self.pickupLocation;
NSString * address = #"";
if ([[desDict objectForKey:#"lat"] length] > 0 && [[desDict objectForKey:#"lon"] length] > 0) {
address = [NSString stringWithFormat:#"%#,%#",[desDict objectForKey:#"lat"], [desDict objectForKey:#"lon"]];
} else if ([desDict[#"address"] length] > 0 && [desDict[#"address"] rangeOfString:#"{"].location == NSNotFound) {
address = [desDict objectForKey:#"address"];
} else {
address = #"NULL";
}
return address;
}
- (NSString*) getCurrentLocation {
return [NSString stringWithFormat:#"%f,%f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
- (MyAnnotation*) getCurrentLocationAnnotation {
MyAnnotation * ann = [[MyAnnotation alloc] init];
CLLocationCoordinate2D location = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
[ann setCoordinate:location];
ann.title = #"My Current Location";
ann.subtitle = #"";
return ann;
}
#end
The problem is that you are setting the map's visible region by calling showAnnotations. This conflicts with the user zooming.

Changing pin color when selecting annotation pin

My app is a map view where the user can enter an address which will put a purple pin on the map for the HQ. Secondly, the user can enter any address, which will put a red pin on the map. I would like to be able to change the pin color of the red pins to either red, green, or purple.
I stumbled across a tutorial that will allow the user to select an annotation pin and change its pin color by displaying a modal view. I followed the tutorial meticulously, but for some reason, it is not working correctly. The modal view with the pin selection is displayed, but when a pin color is selected, the pin color on the map view is not updated. Additionally, instead of using "png" images to display custom pins, I would like to use the built-in standard pins (since that's all I need). How can I adjust my code below to achieve this? I added my entire code.
FieldMapController.m
#import "FieldMapController.h"
#import "CustomAnnotation.h"
#define HQ_latitude #"headquarters_latitude"
#define HQ_longitude #"headquarters_longitude"
#define HQ_coordinates #"headquarters_coordinates"
#import "PinSelectionViewController.h"
#interface FieldMapController ()
#end
#implementation FieldMapController
#synthesize mapView;
#synthesize searchBar;
#synthesize geocoder = _geocoder;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//ACCESS SAVED DATA FROM NSUSERDEFAULTS
-(void)viewWillAppear:(BOOL)animated{
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];
if ([uDefaults boolForKey:#"headquarters_coordinates"])
{
CLLocationCoordinate2D savedCoordinate;
savedCoordinate.latitude = [uDefaults doubleForKey:#"headquarters_latitude"];
savedCoordinate.longitude = [uDefaults doubleForKey:#"headquarters_longitude"];
NSLog(#"Your HQ is at coordinates %f and %f",savedCoordinate.latitude, savedCoordinate.longitude);
CustomAnnotation *annHq =[[CustomAnnotation alloc] init];
annHq.title=#"HQ";
annHq.subtitle=#"";
annHq.coordinate= savedCoordinate;
[mapView addAnnotation:annHq];
MKCoordinateRegion viewRegion = {{0.0, 0.0}, {0.0, 0.0}};
viewRegion.center.latitude = savedCoordinate.latitude;
viewRegion.center.longitude = savedCoordinate.longitude;
viewRegion.span.longitudeDelta = 0.5f;
viewRegion.span.latitudeDelta = 0.5f;
[self.mapView setRegion:viewRegion animated:YES];
[self.mapView setDelegate:self];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.mapView.delegate = self;
self.searchBar.delegate = self;
//SEARCH BAR TOOLBAR WITH "DONE" AND "CANCEL" BUTTON
UIToolbar* searchToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
searchToolbar.barStyle = UIBarStyleBlackTranslucent;
searchToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithTitle:#"Cancel" style:UIBarButtonItemStyleBordered target:self action:#selector(cancelSearchBar)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
nil];
[searchToolbar sizeToFit];
searchBar.inputAccessoryView = searchToolbar;
}
//WHEN PUSHING THE "CANCEL" BUTTON IN THE SEARCH BAR
-(void)cancelSearchBar
{
[searchBar resignFirstResponder];
searchBar.text = #"";
}
//PREPARE SEGUE FOR THE PIN SELECTOR VIEW
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"ShowPinChoicesSegue"])
{
PinSelectionViewController *pinVC = [segue destinationViewController];
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)sender;
pinVC.currentPinType = selectedAnnotation.pinType;
pinVC.delegate = self;
}
}
//WHAT HAPPENS WHEN THE "SEARCH" BUTTON AT THE SEARCH BAR KEYBOARD IS TAPPED
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
//Forward Geocoder
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *address = [NSString stringWithFormat:#"%#", self.searchBar.text];
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
//Display Coordinates in Console
NSLog (#"%f %f", coordinate.latitude, coordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = coordinate;
//Create Annotation with Callout Bubble that displays "No Information"
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:coordinate];
[annotation setTitle:#"No Information"];
[[self mapView] addAnnotation:annotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
//Dismiss the Search Bar Keyboard
[self.searchBar resignFirstResponder];
//Delete text in Search Bar
self.searchBar.text = #"";
}
}];
}
//CUSTOM ANNOTATION VIEW
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
if ([annotation isKindOfClass:[CustomAnnotation class]])
{
MKPinAnnotationView *annotationView =
(MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:((CustomAnnotation *)annotation).annotationViewImageName];
if(annotationView == nil)
{
MKPinAnnotationView *customPinView =
[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:((CustomAnnotation *)annotation).annotationViewImageName];
if([[customPinView.annotation title] isEqualToString:#"HQ"])
{
//The pin for the HQ should be purple
customPinView.pinColor = MKPinAnnotationColorPurple;
}
else
{
//All other new pins should be "red" by default
customPinView.image = [UIImage imageNamed:((CustomAnnotation *)annotation).annotationViewImageName];
}
customPinView.canShowCallout = YES;
customPinView.animatesDrop = YES;
//Right Callout Accessory Button
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
customPinView.rightCalloutAccessoryView = rightButton;
return customPinView;
}
else
{
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
//SHOW ACCESSORY VIEW WHEN BUTTON ON CALLOUT BUBBLE IS TAPPED
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
if (![view.annotation isKindOfClass:[CustomAnnotation class]])
return;
CustomAnnotation *customAnnotation = (CustomAnnotation *)view.annotation;
if (control.tag == 0)
{
[self performSegueWithIdentifier:#"ShowPinChoicesSegue" sender:customAnnotation];
}
else
{
[self onRightCalloutAccessoryViewTouched:control];
}
}
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if(![view.annotation isKindOfClass:[CustomAnnotation class]])
return;
if (!view.rightCalloutAccessoryView)
{
UIButton *rightViewButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 48.0, 32.0)];
[rightViewButton addTarget:self action:#selector(onRightCalloutAccessoryViewtouched:) forControlEvents:UIControlEventTouchUpInside];
rightViewButton.tag = 1;
view.rightCalloutAccessoryView = rightViewButton;
}
}
-(void)onRightCalloutAccessoryViewTouched:(id)sender
{
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)[mapView.selectedAnnotations objectAtIndex:0];
[self performSegueWithIdentifier:#"ShowPinChoicesSegue" sender:selectedAnnotation];
}
- (void)viewDidUnload
{
self.mapView = nil;
self.searchBar = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//BUTTON TO SELECT NEW HQ
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Select Headquarters"
message:#"Enter Address"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeDefault];
[alert show];
}
//REMOVING ALL PINS EXCEPT USER LOCATION
- (IBAction)resetPins:(UIBarButtonItem *)sender
{
id userLocation = [mapView userLocation];
NSMutableArray *pins = [[NSMutableArray alloc] initWithArray:[mapView annotations]];
if ( userLocation != nil )
{
[pins removeObject:userLocation]; //avoid removing user location
}
[mapView removeAnnotations:pins];
pins = nil;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_coordinates];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_longitude];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_latitude];
}
//ALERT VIEW TO ENTER ADDRESS OF HQ
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter HQ Address";
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *hqAddress = [NSString stringWithFormat:#"%#", field.text];
[self.geocoder geocodeAddressString:hqAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D hqCoordinate = location.coordinate;
NSLog (#"Your new HQ is at coordinates %f and %f", hqCoordinate.latitude, hqCoordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = hqCoordinate;
MKPointAnnotation *hqAnnotation = [[MKPointAnnotation alloc] init];
[hqAnnotation setCoordinate:hqCoordinate];
[hqAnnotation setTitle:#"HQ"];
[[self mapView] addAnnotation:hqAnnotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
//Save to NSUserDefaults
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];
[uDefaults setDouble:hqCoordinate.latitude forKey:HQ_latitude];
[uDefaults setDouble:hqCoordinate.longitude forKey:HQ_longitude];
[uDefaults setBool:YES forKey:HQ_coordinates];
[uDefaults synchronize];
}
}];
}
else
{
//any actions for "Cancel"
}
}
//DEFINES WHAT SELECTING THE NEW PIN COLOR DOES
-(void)userDidSelectPinType:(AnnotationPinType)aPinType
{
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)[mapView.selectedAnnotations objectAtIndex:0];
selectedAnnotation.pinType = aPinType;
[mapView removeAnnotation:selectedAnnotation];
[mapView addAnnotation:selectedAnnotation];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#end
CustomAnnotation.m
#import "CustomAnnotation.h"
#import <CoreLocation/CoreLocation.h>
#implementation CustomAnnotation
#synthesize title, subtitle, coordinate;
#synthesize pinType;
-(id) initWithCoordinate:(CLLocationCoordinate2D)aCoordinate title:(NSString *)aTitle subtitle:(NSString *)aSubtitle
{
if ((self = [super init]))
{
self.title = aTitle;
self.coordinate = aCoordinate;
self.subtitle = aSubtitle;
}
return self;
}
- (NSString *)annotationViewImageName
{
switch (self.pinType)
{
case 0:
return #"Red_Pin.png";
break;
case 1:
return #"Green_Pin.png";
break;
case 2:
return #"Purple_Pin.png";
break;
default:
break;
}
}
- (NSString *)title
{
return title;
}
- (NSString *)subtitle
{
return subtitle;
}
#end
PinSelectionViewController.m
#import "PinSelectionViewController.h"
#interface PinSelectionViewController ()
#end
#implementation PinSelectionViewController
#synthesize delegate;
#synthesize currentPinType;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (void)tableView:(UITableView *) tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row ==currentPinType)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.delegate userDidSelectPinType:indexPath.row];
}
#end
PinSelectionDelegateProtocol.h
#import <Foundation/Foundation.h>
typedef enum
{
RED_PIN,
GREEN_PIN,
PURPLE_PIN
} AnnotationPinType;
#protocol PinSelectionDelegate <NSObject>
#required
-(void)userDidSelectPinType:(AnnotationPinType)aPinType;
#end
The problem I see is early on in your viewForAnnotation method. You correctly reuse annotationviews but incorrectly assume that the reused view is configured properly. When you check if the view is nil you only configure brand new ones to have the pin colour that matches the annotation's name. What you need to do is check if it is nil, if is then make a new one and close that if. Then make sure both new and reused annotationviews have their pin colour, title, accessory view etc set up as you want it for that annotation.
Also you can't set the .image of an MKPinAnnotationView, it'll just get overwritten. If you really want to set a custom image you have to use a regular MKAnnotationView. If you are ok with using the standard red, green and blue pins then just set the .pinColor to whatever you want.

Draw polyline in mapview iOS 6

Hi I'm doing an app that must to show a map with the route. I parsed a Json to obtain the points to draw the polyline. I found a a code in the web to draw this polyline. The code I found it's on this link: http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/
Where it says "Create the MKPolyline annotation" I tried to import this in my app, but I'm having problems to create the array of the coordinates. My method is this:
- (void)createMKpolylineAnnotation {
NSInteger numberOfSteps = self.path.count;
CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * numberOfSteps);
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [self.path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coords[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coords count:numberOfSteps];
[self.mapView addOverlay:polyLine];
}
When I try to look the value of coords is setted only the first time, why's that?
Can you help me to solve this problem or i should make in another mode?
I post here the code of the view controller that handle the map view.
MapViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface MapViewController : UIViewController <MKMapViewDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) NSString *fromCity;
#property (nonatomic, strong) NSString *toCity;
- (IBAction)chooseKindOfMap:(id)sender;
#end
MapViewController.m
#import "MapViewController.h"
#import "AppDelegate.h"
#import "PlaceAnnotation.h"
#interface MapViewController ()
#property (nonatomic, strong)NSMutableArray *mapAnnotation;
#property (nonatomic) BOOL needUpdateRegion;
#property (nonatomic, strong)NSMutableArray *path;
#end
#implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self parseGoogleJsonToObtainPointsForPolyline];
[self.mapView setDelegate:self];
self.needUpdateRegion = YES;
//[self centerMap];
self.mapAnnotation = [[NSMutableArray alloc]initWithCapacity:2];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSLog(#"%d", appDelegate.dataForMap.count);
NSArray* coords = [self getCoords:appDelegate.dataForMap];
NSLog(#"coords = %#", coords);
PlaceAnnotation *fromPlace = [[PlaceAnnotation alloc] initWithCoordinateAndName:coords[0] andLong:coords[1] andName:self.fromCity];
PlaceAnnotation *toPlace = [[PlaceAnnotation alloc] initWithCoordinateAndName:coords[2] andLong:coords[3] andName:self.toCity];
[self.mapAnnotation insertObject:fromPlace atIndex:0];
[self.mapAnnotation insertObject:toPlace atIndex:1];
NSLog(#"mapAnnotation.count: %d", self.mapAnnotation.count);
if (self.mapAnnotation) {
[self.mapView removeAnnotations:self.mapView.annotations];
}
[self.mapView addAnnotation:self.mapAnnotation[0]];
[self.mapView addAnnotation:self.mapAnnotation[1]];
NSLog(#"MapAnnotation = %#", self.mapView.annotations);
[self updateRegion];
[self createMKpolylineAnnotation];
}
//- (void)viewDidAppear:(BOOL)animated {
// [super viewDidAppear:animated];
// if (self.needUpdateRegion) [self updateRegion];
//}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
pin.pinColor = MKPinAnnotationColorRed;
return pin;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
MKPinAnnotationView *ulv = [mapView viewForAnnotation:mapView.userLocation];
ulv.hidden = YES;
}
- (NSArray*)getCoords:(NSDictionary*)data {
NSArray *legs = [data objectForKey:#"legs"];
NSDictionary *firstZero = [legs objectAtIndex:0];
NSDictionary *endLocation = [firstZero objectForKey:#"end_location"];
NSDictionary *startLocation = [firstZero objectForKey:#"start_location"];
NSString *latFrom = [startLocation objectForKey:#"lat"];
NSString *lngFrom = [startLocation objectForKey:#"lng"];
NSString *latTo = [endLocation objectForKey:#"lat"];
NSString *lngTo = [endLocation objectForKey:#"lng"];
return #[latFrom,lngFrom,latTo,lngTo];
}
- (void)centerMap {
MKCoordinateRegion region;
region.center.latitude = 41.178654;
region.center.longitude = 11.843262;
region.span.latitudeDelta = 11.070406;
region.span.longitudeDelta = 12.744629;
[self.mapView setRegion:region];
}
- (IBAction)chooseKindOfMap:(id)sender {
if ([sender tag] == 0) {
self.mapView.mapType = MKMapTypeStandard;
}
if ([sender tag] == 1) {
self.mapView.mapType = MKMapTypeSatellite;
}
if ([sender tag] == 2) {
self.mapView.mapType = MKMapTypeHybrid;
}
}
- (void)updateRegion
{
self.needUpdateRegion = NO;
CGRect boundingRect;
BOOL started = NO;
for (id <MKAnnotation> annotation in self.mapView.annotations) {
CGRect annotationRect = CGRectMake(annotation.coordinate.latitude, annotation.coordinate.longitude, 0, 0);
if (!started) {
started = YES;
boundingRect = annotationRect;
} else {
boundingRect = CGRectUnion(boundingRect, annotationRect);
}
}
if (started) {
boundingRect = CGRectInset(boundingRect, -0.2, -0.2);
if ((boundingRect.size.width < 20) && (boundingRect.size.height < 20)) {
MKCoordinateRegion region;
region.center.latitude = boundingRect.origin.x + boundingRect.size.width / 2;
region.center.longitude = boundingRect.origin.y + boundingRect.size.height / 2;
region.span.latitudeDelta = boundingRect.size.width;
region.span.longitudeDelta = boundingRect.size.height;
[self.mapView setRegion:region animated:YES];
}
}
}
- (void)parseGoogleJsonToObtainPointsForPolyline {
NSDictionary *polyline;
NSMutableArray *points = [[NSMutableArray alloc]init];;
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSArray *legs = [appDelegate.dataForMap objectForKey:#"legs"];
NSDictionary *firstZero =[legs objectAtIndex:0];
NSArray *steps = [firstZero objectForKey:#"steps"];
for (int i = 0; i < steps.count; i++) {
polyline = [steps[i] objectForKey:#"polyline"];
[points addObject:polyline[#"points"]];
NSLog(#"POINTS = %#", polyline[#"points"]);
self.path = [self decodePolyLine:points[i]];
}
NSLog(#"path = %#", self.path);
}
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr {
NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
[encoded appendString:encodedStr];
[encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init];
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[array addObject:location];
}
return array;
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
polylineView.strokeColor = [UIColor redColor];
polylineView.lineWidth = 1.0;
return polylineView;
}
- (void)createMKpolylineAnnotation {
NSInteger numberOfSteps = self.path.count;
CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * numberOfSteps);
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [self.path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coords[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coords count:numberOfSteps];
[self.mapView addOverlay:polyLine];
}
#end
I used the AppDelegate to have the Json (I parsed it in another class)
Here is a tutorial how to add a polyline to a mapView. Hope this helps!
EDIT:
Unfortunately, the link provided above is now broken, and I am not able to find the tutorial referred to.
simple, just copy and paste my code and modify some variables
- (IBAction)traceRoute:(UIButton *)sender {
double latDouble = 39.7540615;
double lngDouble = -8.8059587;
// double latDouble = [self.sheetDetail.data.locationLat doubleValue];
// double lngDouble = [self.sheetDetail.data.locationLng doubleValue];
CLLocationCoordinate2D c2D = CLLocationCoordinate2DMake(latDouble, lngDouble);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:c2D addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:#"Mobile Edge"];
MKPlacemark *placemark2;
MKMapItem *mapItem2;
if(kIS_OS_8_OR_LATER) {
placemark2 = [[MKPlacemark alloc] initWithCoordinate:_userLoc addressDictionary:nil];
mapItem2 = [[MKMapItem alloc] initWithPlacemark:placemark2];
[mapItem2 setName:#"Me"];
} else {
placemark2 = [[MKPlacemark alloc] initWithCoordinate:_mapView.userLocation.coordinate addressDictionary:nil];
mapItem2 = [[MKMapItem alloc] initWithPlacemark:placemark2];
[mapItem2 setName:#"Me"];
}
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = mapItem2;
request.destination = mapItem;
request.requestsAlternateRoutes = NO;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:
^(MKDirectionsResponse *response, NSError *error) {
if (error) {
// Handle error
[[NSNotificationCenter defaultCenter] postNotificationName:#"finishedLocationRoute" object:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(#"Route error title", nil)
message: NSLocalizedString(#"Route error", nil)
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else {
for (MKRoute *route in response.routes)
{
//MKMapPoint middlePoint = route.polyline.points[route.polyline.pointCount/2];
//[self createAndAddAnnotationForCoordinate:MKCoordinateForMapPoint(middlePoint) andRoute:route];
[self.mapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
}
//notifies parent menu
//[[NSNotificationCenter defaultCenter] postNotificationName:#"finishedLocationRoute" object:nil];
}
}];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id)overlay
{
if (![overlay isKindOfClass:[MKPolygon class]]) {
MKPolyline *route = overlay;
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
renderer.strokeColor = [UIColor blueColor];
renderer.lineWidth = 5.0;
return renderer;
} else {
return nil;
}
}

Can't get viewForAnnotation to fire after initial user location firing

I have this code:
// MapViewController.h
#import <Foundation/Foundation.h>
#import "MyCLController.h"
#import <MapKit/MapKit.h>
#class ShowsContainerController;
#interface MapViewController : UIViewController <MyCLControllerDelegate,MKMapViewDelegate> {
MyCLController *locationController;
MKMapView *mapView;
}
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property (assign) BOOL updateMap;
#property (strong) ShowsContainerController *parent;
#end
// MapViewController.m
#import "MapViewController.h"
#import "ShowsContainerController.h"
#define METERS_PER_MILE 1609.344
#implementation MapViewController
#synthesize parent, mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
self.updateMap = YES;
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
mapView.delegate = self;
}
- (void)locationUpdate:(CLLocation *)location {
if( self.updateMap ){
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[mapView setRegion:viewRegion animated:YES];
self.parent = (ShowsContainerController *)self.parentViewController;
[self.parent setLocation:location];
self.updateMap = NO;
}
}
- (void)locationError:(NSError *)error {
NSLog([error localizedDescription]);
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.parent.mapReady = YES;
if( self.parent.locationSet ){
[self.parent callApi];
}
}
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"delegating user location");
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
NSLog(#"delegating pins");
static NSString* ShowAnnotationIdentifier = #"showAnnotationIdentifier";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)
[mapView dequeueReusableAnnotationViewWithIdentifier:ShowAnnotationIdentifier];
if (!pinView)
{
// if an existing pin view was not available, create one
MKPinAnnotationView* customPinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:ShowAnnotationIdentifier];
customPinView.enabled = YES;
customPinView.pinColor = MKPinAnnotationColorRed;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
return customPinView;
}
else
{
pinView.annotation = annotation;
}
return pinView;
}
#pragma mark -
#end
And here's the code adding my pins; it isn't fired until an api call is made, which is after viewDidAppear is fired:
- (void)placeAnnotations:(NSArray *)shows
{
NSEnumerator *e = [shows objectEnumerator];
id show;
NSMutableArray *annotations = [[NSMutableArray alloc] init];
while (show = [e nextObject]) {
double lat = [[[[[show objectForKey:#"venue"] objectForKey:#"location"] objectForKey:#"geo:point"] objectForKey:#"geo:lat"] doubleValue];
double lng = [[[[[show objectForKey:#"venue"] objectForKey:#"location"] objectForKey:#"geo:point"] objectForKey:#"geo:long"] doubleValue];
ShowAnnotation *annotation = [[ShowAnnotation alloc]
initWithCoordinate:CLLocationCoordinate2DMake(lat, lng)
withMap:self.mapController.mapView
withTitle:[show objectForKey:#"title"]
withSubtitle:[[show objectForKey:#"venue"] objectForKey:#"name" ]];
[annotations addObject:annotation];
}
NSLog(#"adding annotations");
[self.mapController.mapView addAnnotations:annotations];
}
The log shows "delegating user location", but never "delegating pins". It doesn't even fire viewForAnnotation more than the one initial time for the user's location.
The delegation seems to be working, otherwise I wouldn't be able to capture this selector, but why is it firing for only the user location and not firing for subsequent annotation additions?

Resources