Custom curent location Annotation pin not updating with core location - objective-c

Trying to add a custom pin for current location, However the location does not update. Even after setting setShowsUserLocation = YES;
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if ([[annotation title] isEqualToString:#"Current Location"]) {
self.image = [UIImage imageNamed:[NSString stringWithFormat:#"cursor_%i.png", [[Session instance].current_option cursorValue]+1]];
}
However, if I set to return nil; everything works fine, but I lose the custom image. I really want to get this to work. Any help would be greatly appreciated.

As you've seen the setShowsUserLocation flag only shows the current location using the default blue bubble.
What you need to do here listen for location updates from the phone and manually reposition your annotation yourself. You can do this by creating a CLLocationManager instance and remove and replace your annotation whenever the Location Manager notifies its delegate of an update:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// update annotation position here
}
To reposition the coordinates, I have a class, Placemark, that conforms to the protocol MKAnnotation:
//--- .h ---
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Placemark : NSObject <MKAnnotation> {
}
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#property (nonatomic, retain) NSString *strSubtitle;
#property (nonatomic, retain) NSString *strTitle;
-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;
- (NSString *)subtitle;
- (NSString *)title;
#end
//--- .m ---
#implementation Placemark
#synthesize coordinate;
#synthesize strSubtitle;
#synthesize strTitle;
- (NSString *)subtitle{
return self.strSubtitle;
}
- (NSString *)title{
return self.strTitle;
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c {
self.coordinate = c;
[super init];
return self;
}
#end
Then in my mapview controller I place the annotation with:
- (void) setPlacemarkWithTitle:(NSString *) title andSubtitle:(NSString *) subtitle forLocation: (CLLocationCoordinate2D) location {
//remove pins already there...
NSArray *pins = [mapView annotations];
for (int i = 0; i<[pins count]; i++) {
[mapView removeAnnotation:[pins objectAtIndex:i]];
}
Placemark *placemark=[[Placemark alloc] initWithCoordinate:location];
placemark.strTitle = title;
placemark.strSubtitle = subtitle;
[mapView addAnnotation:placemark];
[self setSpan]; //a custom method that ensures the map is centered on the annotation
}

Related

Problems with Location Manager

I've been stuck on this problem for ages and I'm sure the reason is that I don't know enough about objective-c. I've only just started using coding with it!
Anyway I'm trying to design an app that tracks the current distance travelled and also displays the route that have been taken using MKPolyLine. I've got MKPolyLine sorted now but the problem I;m having is with getting the current distance. I think the code is OK but I think i'm doing something funny with location manager.
I've done a bit of debugging and found that my second locationManager method does not get called.
Here is the code below, if someone can take a quick look and just point me in the right direct it would be greatly appreciated.
Many Thanks.
.m :
#interface StartCycleViewController ()
#property (nonatomic, strong) CLLocationManager *locationManager;
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) UIView *containerView;
#property (nonatomic, strong) CLLocationManager *distanceManager;
#end
#implementation StartCycleViewController
static double totalDistanceBetween;
#synthesize cycleLocation = _cycleLocation;
#synthesize currentCycleLocation = _currentCycleLocation;
#synthesize mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
[self startCycleLocation];
[mapView setDelegate:self];
self.locations = [NSMutableArray array];
}
- (void)dealloc
{
self.locationManager.delegate = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - startCycleLocation
- (void)startCycleLocation{
if (!_cycleLocation){
_cycleLocation = [[CLLocationManager alloc]init];
_cycleLocation.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
_cycleLocation.distanceFilter = 5;
_cycleLocation.delegate = self;
_startLocation = nil;
}
[_cycleLocation startUpdatingLocation];
}
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"%#",error);
if ( [error code] != kCLErrorLocationUnknown ){
[self stopLocationManager];
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
if (location.horizontalAccuracy < 0)
return;
[self.locations addObject:location];
NSUInteger count = [self.locations count];
if (count > 1) {
// only both to add new location if distance has changed by more than 5 meters
[self.locations addObject:location];
count = [self.locations count];
CLLocationCoordinate2D coordinates[count];
for (NSInteger i = 0; i < count; i++) {
coordinates[i] = [(CLLocation *)self.locations[i] coordinate];
}
MKPolyline *oldPolyline = self.polyline;
self.polyline = [MKPolyline polylineWithCoordinates:coordinates count:count];
[self.mapView addOverlay:self.polyline];
if (oldPolyline)
[self.mapView removeOverlay:oldPolyline];
}
NSLog(#"didUpdateToLocation2: %#", location);
}
- (void) stopLocationManager {
[self.cycleLocation stopUpdatingLocation];
}
#pragma mark - MKMapViewDelegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
NSLog(#"PolyLine Started");
if ([overlay isKindOfClass:[MKPolyline class]])
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
[self.mapView setVisibleMapRect:overlay.boundingMapRect animated:YES];
renderer.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
renderer.lineWidth = 3;
return renderer;
NSLog(#"MKPolyline Rendering");
}
return nil;
}
- (IBAction)stopActivity:(id)sender {
[self stopLocationManager];
NSLog(#"Stopped");
}
-(void)distanceManager:(CLLocationManager *)manager didUpdateLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"Current Distance Started");
if (self.startLocation == nil)
{
totalDistanceBetween = 0;
_startLocation = newLocation;
}
CLLocationDistance distanceBetween = [newLocation distanceFromLocation:_startLocation ];
self.startLocation = newLocation;
totalDistanceBetween += distanceBetween;
NSString *cycleDistanceString = [[NSString alloc]
initWithFormat:#"%f",
totalDistanceBetween];
_CurrentDistance.text = cycleDistanceString;
NSLog(#"cycleDistance is %#", cycleDistanceString);
}
#end
.h :
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <AVFoundation/AVFoundation.h>
#interface StartCycleViewController : UIViewController <NSXMLParserDelegate, CLLocationManagerDelegate, MKMapViewDelegate>
#property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
#property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
#property (nonatomic,strong) CLLocation *currentCycleLocation;
#property (nonatomic,strong) CLLocationManager *cycleLocation;
#property (nonatomic,strong) CLLocation *startLocation;
#property (strong, nonatomic) IBOutlet UILabel *CurrentDistance;
- (IBAction)stopActivity:(id)sender;
#property(nonatomic, strong) MKPolyline *polyline;
#property (nonatomic,strong) NSMutableArray *locations;
#property (nonatomic,strong) NSNumber *currentSpeed;
#property (nonatomic,strong) NSMutableArray *locationHistory;
- (void) stopLocationManager;
#end

Archiving and Unarchiving data/model objects

I'm following the MVCS paradigm for saving and then loading instances of data objects in a Test app related to updating mapping data.
BNRMapPoint.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface BNRMapPoint : NSObject<MKAnnotation, NSCoding>
{
double latitude;
double longitude;
#public NSArray *mapPoints;
}
-(id) initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t subTitle:(NSString *)st;
//this is required property in MKAnnotation Protocol
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
//this is an optional property in MKAnnotation Protocol
#property (nonatomic, copy) NSString *title;
//this is an optional property in MKAnnotation Protocol
#property (nonatomic,readonly,copy) NSString *subTitle;
#end
BNRMapPoint.m (Model)
#import "BNRMapPoint.h"
#implementation BNRMapPoint
#synthesize coordinate=_coordinate;
#synthesize title=_title;
#synthesize subtitle=_subtitle;
-(void)encodeWithCoder:(NSCoder *)aCoder{
latitude = self.coordinate.latitude;
longitude = self.coordinate.longitude;
[aCoder encodeObject:self.title forKey:#"title"];
[aCoder encodeObject:_subTitle forKey:#"subTitle"];
[aCoder encodeDouble: latitude forKey:#"latitude"];
[aCoder encodeDouble:longitude forKey:#"longitude"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self= [super init]) {
[self setTitle:[aDecoder decodeObjectForKey:#"title"]];
self->_subTitle= [aDecoder decodeObjectForKey:#"subTitle"];
latitude= [aDecoder decodeDoubleForKey:#"latitude"];
longitude= [aDecoder decodeDoubleForKey:#"longitude"];
}
return self;
}
-(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t subTitle:(NSString *)st{
if (self= [super init]) {
self.coordinate=c;
self.title=t;
_subtitle=st;
}
return self;
}
-(id) init{
return [self initWithCoordinate:CLLocationCoordinate2DMake(43.07, -89.32) title:#"Hometown" subTitle:self.subtitle];
}
#end
WhereamiViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "BNRMapPoint.h"
#import "RootObject.h"
#interface WhereamiViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,UITextFieldDelegate>
{
#public RootObject *rootObj;
CLLocationManager *locationManager;
IBOutlet MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UITextField *locationTitleField;
}
-(IBAction)buttonDidGetPressed:(id)sender;
-(BOOL)textFieldShouldReturn:(UITextField *)textField;
-(void)findLocation;
-(void)foundLocation:(CLLocation *)loc;
#end
WhereamiViewController.m (ViewController)
#import "WhereamiViewController.h"
#interface WhereamiViewController ()
#end
#implementation WhereamiViewController
-(IBAction)buttonDidGetPressed:(UISegmentedControl *)sender{//Silver challenge
NSLog(#"%#",NSStringFromSelector(_cmd));
if([sender selectedSegmentIndex]==0){
[worldView setMapType:MKMapTypeStandard];
}
else if([sender selectedSegmentIndex]==1){
[worldView setMapType:MKMapTypeHybrid];
}
else if([sender selectedSegmentIndex]==2){
[worldView setMapType:MKMapTypeSatellite];
}
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
NSLog(#"%#", NSStringFromSelector(_cmd));
if (self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
rootObj= [[RootObject alloc] init];
locationManager= [[CLLocationManager alloc] init];
[locationManager setDelegate:self];//self is Whereamicontroller. The delegate pointer is of type id<CLLocationManagerDelegate> and is an ivar of CLLocationManager.
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
NSLog(#"test");
return self;
}
-(void) viewDidLoad{
// [worldView setMapType:MKMapTypeSatellite]; Bronze challenge
[worldView setShowsUserLocation:YES];
}
-(void)findLocation{
NSLog(#"%#",NSStringFromSelector(_cmd));
[locationManager startUpdatingLocation];//This calls locationManager:didUpdateLocations:
NSLog(#"location updated");
[activityIndicator startAnimating];
[locationTitleField setHidden:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(#"%#",NSStringFromSelector(_cmd));
[self findLocation];
[textField resignFirstResponder];
return YES;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
NSLog(#"%#",NSStringFromSelector(_cmd));
CLLocationCoordinate2D centerCoordinate= [[userLocation location] coordinate]; //get the coordinate of current location.
MKCoordinateSpan span= MKCoordinateSpanMake(250, 250);//Structure members
MKCoordinateRegion mapPortionToDisplay= MKCoordinateRegionMakeWithDistance(centerCoordinate, span.latitudeDelta, span.longitudeDelta);//span.latitudeDelta=250 and span.longitudeDelta=250
[worldView setRegion:mapPortionToDisplay animated:YES];
// [worldView setRegion:mapPortionToDisplay];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
NSLog(#"%#",NSStringFromSelector(_cmd));
NSLog(#"Heading %#",newHeading);
}
-(void)foundLocation:(CLLocation *)loc{
NSLog(#"%#",NSStringFromSelector(_cmd));
CLLocationCoordinate2D coord= [loc coordinate];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
NSDate *currentDate= [[NSDate alloc] init];
[formatter setDefaultDate:currentDate];
BNRMapPoint *bmp= [[BNRMapPoint alloc] initWithCoordinate:coord title:[locationTitleField text] subTitle:[[formatter defaultDate] description]];
[rootObj.mapPoints addObject:bmp];
[worldView addAnnotation:bmp];
MKCoordinateRegion region= MKCoordinateRegionMakeWithDistance(coord,250,250);
[worldView setRegion:region animated:YES];
//RESET the UI
[locationTitleField setText:#" "];
[activityIndicator stopAnimating];
[locationTitleField setHidden:NO];
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ //CLLocationManagerDelegate method implementation
NSLog(#"%#", NSStringFromSelector(_cmd));
// NSTimeInterval t0=[[locations lastObject] timeIntervalSinceNow];
NSLog(#"%#",(CLLocation *)[locations lastObject]);
NSTimeInterval t= [[(CLLocation *)[locations lastObject] timestamp] timeIntervalSinceNow];
if (t<-180) {
return; //No op
}
[self foundLocation:[locations lastObject]];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"Could not find location: %#",error);//CLLocationManagerDelegate method implementation
}
#end
RootObject.h
#import <Foundation/Foundation.h>
#interface RootObject : NSObject
#property NSMutableArray *mapPoints;
-(BOOL)saveChanges;
-(NSString *)dataObjectArchivePath;
#end
RootObject.m (Store)
#import "RootObject.h"
#implementation RootObject
#synthesize mapPoints;
-(NSString *)dataObjectArchivePath{
NSArray *documentDirectories= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory= [documentDirectories objectAtIndex:0];
NSString *finalPath= [documentDirectory stringByAppendingPathComponent:#"items.archive"];
return finalPath;
}
-(BOOL)saveChanges{
NSString *path= [self dataObjectArchivePath];
return [NSKeyedArchiver archiveRootObject:self.mapPoints toFile:path];writing to the file items.archive
}
-(id)init{
if (self=[super init]) {
NSString *path= [self dataObjectArchivePath];
self.mapPoints= [NSKeyedUnarchiver unarchiveObjectWithFile:path];//reading from the file items.archive
if (!self.mapPoints) {
self.mapPoints= [[NSMutableArray alloc] init];
}
}
return self;
}
#end
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
NSLog(#"%#",NSStringFromSelector(_cmd));
BOOL success= [[BNRItemStore sharedStore] saveChanges];
if (success) {
NSLog(#"Saved all of the BNRItems");
}
else{
NSLog(#"Could not save any of the BNRItems");
}
}
In the above code, the saveChanges method is called from application: didEnterBackground:. So i haven't made a singleton object for the Store (RootObject). But i instantiated it in the designated initializer of viewController. The data to be archived is BNRMapPoint objects. On the entering background state, the code did save the objects successfully. However after the relaunching the app, the initWithCoder is where its getting stuck. The app crashes when it comes to reading the previously saved MapPoint objects. Pls help.. I've checked almost possible. Don't know what to do. I'm stuck.
So the problem is that you have:
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
And you are trying to use setter on read only property:
self.coordinate=c;
This is why it says that unrecognized selector is send - becuase it's readonly so setter doesn't exists. Using property this was is the same as calling:
[self setCoordinate:c]
Just make property assignable

signal SIGABRT, when trying to get distance to annotations

I'm trying to calulate the distance between the userLocation and my annotations (from plist), But every time im run the mapView im getting signal SIGABRT error.
I'm doing the calculate in my mapViewController.m and want to show the calculated values in my tableViewController.
In my Annotations.h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
#interface Annotation : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, assign) CLLocationDistance distance;
#property (nonatomic, copy) NSString * title;
#property (nonatomic, copy) NSString * subtitle;
#property (nonatomic, copy) NSString * sculptureIdKey;
#end
I'm synthesize distance = _distance; in my Annotations.m file.
In my mapViewController.m im doing the calculations
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
for (Annotation *annotation in self.mapView.annotations)
{
CLLocationCoordinate2D coord = [annotation coordinate];
CLLocation *annLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
annotation.distance = [annLocation distanceFromLocation:newLocation];
CLLocationDistance calculatedDistance = [annLocation distanceFromLocation:newLocation];
annotation.distance = calculatedDistance;
NSLog(#"Calculated Distance:%.2f m\n", calculatedDistance);
}
}
And in my tableViewController.h
#import "mainViewController.h"
#import "mapViewController.h"
#import "Annotation.h"
#interface ListViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>
#property (readonly) CLLocationCoordinate2D selectedCoordinate;
#property (nonatomic, assign) CLLocationDistance distance;
#property (nonatomic, strong) CLLocationManager *locationManager;
#property (nonatomic, strong) CLLocation *userLocation;
#property (nonatomic, strong) NSArray *locationsArray;
#end
And tableViewController.m
#import "ListViewController.h"
#import "customCell.h"
#interface ListViewController ()
#end
#implementation ListViewController
#synthesize locationsArray = _locationsArray;
#synthesize locationManager = _locationManager;
#synthesize selectedCoordinate = _selectedCoordinate;
#synthesize distance = _distance;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.locationsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (!cell)
{
cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.customTitle.text = [[self.locationsArray objectAtIndex:indexPath.row] valueForKey:#"sculptureNameKey"];
cell.customSubTitle.text = [[self.locationsArray objectAtIndex:indexPath.row] valueForKey:#"sculptureAddressKey"];
cell.distanceLabel.text = [NSString stringWithFormat:#"Nice distance:%f m\n", _distance];
return cell;
}
My output in log is as follow
2013-02-15 11:05:50.769 TalkingSculpture[11639:c07] Calculated Distance:83971.36 m
2013-02-15 11:05:50.770 TalkingSculpture[11639:c07] Calculated Distance:83406.16 m
2013-02-15 11:05:50.771 TalkingSculpture[11639:c07] Calculated Distance:86002.30 m
2013-02-15 11:05:50.771 TalkingSculpture[11639:c07] -[MKUserLocation setDistance:]: unrecognized selector sent to instance 0xee4f080
2013-02-15 11:05:50.772 TalkingSculpture[11639:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MKUserLocation setDistance:]: unrecognized selector sent to instance 0xee4f080'
*** First throw call stack:
(0x1b44012 0x1460e7e 0x1bcf4bd 0x1b33bbc 0x1b3394e 0x3ef8 0x3637e 0x3593f 0x339c5 0x2f175 0x1b03920 0x1ac6d31 0x1aeac51 0x1ae9f44 0x1ae9e1b 0x1a9e7e3 0x1a9e668 0x3a4ffc 0x43ed 0x2535)
libc++abi.dylib: terminate called throwing an exception
In your for-loop where you set the annotation distance, you need to check that the annotation is not MKUserLocation since it is one of self.mapView.annotations. Otherwise, "annotation.distance" will apply to MKUserLocation, which doesn't have a distance property. Here's the update to your code:
for (Annotation *annotation in self.mapView.annotations)
{
if (![annotation isKindOfClass:[MKUserLocation class]]) //<-- Need this check
{
CLLocationCoordinate2D coord = [annotation coordinate];
CLLocation *annLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
annotation.distance = [annLocation distanceFromLocation:newLocation];
CLLocationDistance calculatedDistance = [annLocation distanceFromLocation:newLocation];
annotation.distance = calculatedDistance;
NSLog(#"Calculated Distance:%.2f m\n", calculatedDistance);
}
}

checking which map view annotation is tapped on mkmapview

I am having problem in knowing which annotation is tapped on MKMapView.
let me explain my problem, there is a simple view controller on which map view is loaded.
my annotation class "MapViewAnnotation.h" is as follows
#interface MapViewAnnotation : NSObject <MKAnnotation>
{
NSString *title;
CLLocationCoordinate2D coordinate;
NSString *sID;
NSString *zipCode;
}
#property (nonatomic, copy) NSString *title;
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, retain) NSString *sID;
#property (nonatomic, retain) NSString *zipCode;
- (id)initWithTitle:(NSString *)titleOfPin andStoreId:(NSString *)storeIdForDetails andCoordinate:(CLLocationCoordinate2D)coordinateOfPin andZipCode:(NSString *)zip;
here is my "MapViewAnnotation.m" file.
#import "MapViewAnnotation.h"
#import <MapKit/MapKit.h>
#implementation MapViewAnnotation
#synthesize title, coordinate,storeId,zipCode;
- (id)initWithTitle:(NSString *)titleOfPin andStoreId:(NSString *)storeIdForDetails andCoordinate:(CLLocationCoordinate2D)coordinateOfPin andZipCode:(NSString *)zip
{
[super init];
title = titleOfPin;
coordinate = coordinateOfPin;
sID = storeIdForDetails;
zipCode = zip;
return self;
}
-(void)dealloc
{
[title release];
[super dealloc];
}
#end
and this is my viewcontroller.m file
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
//I want to access the sID property of that annotation here. PLEASE HELP ME HOW CAN I DO THAT
if (!storeDetailControllerObject) {
storeDetailControllerObject = [[StoreDetailController alloc]init];
}
// storeDetailControllerObject.storeId = [view.annotation storeId];
[self.navigationController pushViewController:storeDetailControllerObject animated:YES];
From the MKMapViewDelegate protocol reference:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view;
If you handle the event in this method you may know which annotation was selected.
You have to set the MKMapView's delegate and to declare that you class implements the MKMapViewDelegate.
This should work:
MapViewAnnotation *mapViewAnnotation = (MapViewAnnotation*)view.annotation;
if( [mapViewAnnotation isKindOfClass:[MapViewAnnotation class]] ){
storeDetailControllerObject.storeId = mapViewAnnotation.storeId;
}

Adding more annotations to UIMapView

I want to add more annotations to my mapview. I'm working with a class Annotation where there is a method addAnnotation. This method is being called in my UIViewController when I want to add a new annotation.
But for some reason, only the annotation I added last, is displayed.
Annotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
#interface Annotation : NSObject {
CLLocationCoordinate2D cooridnate;
NSString *title;
NSString *subtitle;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property (nonatomic, retain) NSMutableArray *locations;
-(void)addAnnotation: (NSString *)initTitle : (NSString *)initSubtitle : (CLLocationCoordinate2D) initCoordinate;
#end
Annotation.m
#import "Annotation.h"
#implementation Annotation
#synthesize coordinate, title, subtitle, locations;
-(void)addAnnotation: (NSString *)initTitle : (NSString *)initSubtitle : (CLLocationCoordinate2D) initCoordinate {
locations = [[NSMutableArray alloc] init];
self.coordinate = initCoordinate;
self.title = [NSString stringWithFormat:#"%#", initTitle];
self.subtitle = [NSString stringWithFormat:#"%#", initSubtitle];
[locations addObject:self]; // add all my anotations with location to an array
}
#end
Method in my UIViewController
#import "MapViewController.h"
#interface MapViewController ()
#end
#implementation MapViewController
#synthesize mapView;
#pragma mark - ViewController methods
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self initMapView];
ann = [[Annotation alloc] init]; // making place in memory
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UIMapController methods
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView {
[self createAnnotations];
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]]) {
//If annotation = user position ==> DON'T CHANGE
return nil;
}
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorRed;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[advertButton addTarget:self action:#selector(showInfo:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = NO;
MyPin.animatesDrop= FALSE;
MyPin.canShowCallout = YES;
return MyPin;
}
#pragma mark - MY Methods
-(void) initMapView {
[mapView setMapType:MKMapTypeStandard]; // standaard maptype
[mapView setScrollEnabled:YES];
[mapView setZoomEnabled:YES];
[mapView setDelegate:self]; // gegevens van de map terugsturen naar deze viewController en de gebruiker
[mapView setShowsUserLocation:YES];
[self focusWorld];
}
-(void) createAnnotations {
[self initSomeExamples];
[self.mapView addAnnotations: ann.locations];
}
-(void) focusWorld {
MKCoordinateRegion worldRegion = MKCoordinateRegionForMapRect(MKMapRectWorld); // regio instellen op World
mapView.region = worldRegion; // regio doorgeven naar onze mapView
}
-(void) initSomeExamples {
// Washington
l1.latitude = 38.892102;
l1.longitude = -77.029953;
// Antwerp
l2.latitude = 51.219787;
l2.longitude = 4.411011;
// Egypt
l3.latitude = 29.993002;
l3.longitude = 31.157227;
// Brazil
l4.latitude = -22.900846;
l4.longitude = -43.212662;
[ann addAnnotation:#"America has a new President !" :#"Washington DC" :l1]; // call method to add an annotation with these parameters
[ann addAnnotation:#"Revolutionary app by Belgium student" :#"Antwerp" :l2];
[ann addAnnotation:#"The new Arabic revolution" :#"Egypt, Tahir square" :l3];
[ann addAnnotation:#"World Championchip football" :#"Rio de Janeiro" :l4];
}
#pragma mark - ACTIONS
-(void)showInfo:(id)sender {
NSLog(#"Show info");
}
#end
You don't need locations #property and - addAnnotation: method. One MKAnnotation object represents a location.
My suggestion is to modify Annotation class accordingly, as well as conforming and create it's objects as many as number of locations you would like to annotate.
Remove locations #property and -addAnnotation: method from Annotation.h/m
Annotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
#interface Annotation : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
-(id) initWithTitle: (NSString *)initTitle : (NSString *)initSubtitle : (CLLocationCoordinate2D) initCoordinate;
#end
Annotation.m
#import "Annotation.h"
#implementation Annotation
#synthesize coordinate, title, subtitle;
-(id) initWithTitle: (NSString *)initTitle : (NSString *)initSubtitle : (CLLocationCoordinate2D) initCoordinate {
self = [super init];
if ( self ) {
self.coordinate = initCoordinate;
self.title = [NSString stringWithFormat:#"%#", initTitle];
self.subtitle = [NSString stringWithFormat:#"%#", initSubtitle];
}
return self; // correction appreciated.
}
#end
Some methods changed in your view controller
-(void) initSomeExamples {
// Washington
l1.latitude = 38.892102;
l1.longitude = -77.029953;
// Antwerp
l2.latitude = 51.219787;
l2.longitude = 4.411011;
// Egypt
l3.latitude = 29.993002;
l3.longitude = 31.157227;
// Brazil
l4.latitude = -22.900846;
l4.longitude = -43.212662;
NSArray *annotations = #[
[[Annotation alloc] initWithTitle:#"America has a new President !" :#"Washington DC" :l1],
[[Annotation alloc] initWithTitle:#"Revolutionary app by Belgium student" :#"Antwerp" :l2],
[[Annotation alloc] initWithTitle:#"The new Arabic revolution" :#"Egypt, Tahir square" :l3],
[[Annotation alloc] initWithTitle:#"World Championchip football" :#"Rio de Janeiro" :l4] ];
// Adding 4 annotation objects
[self.mapView addAnnotations:annotations];
}
-(void) createAnnotations {
[self initSomeExamples];
// Annotations are added in -initSomeExamples method.
}