How to center region in iOS6 - ios

I have a problem with centering the map to a particular region. I don't know where the problem is
Map.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface Map : UIViewController {
MKMapView * mapView;
}
#property(nonatomic,retain) IBOutlet MKMapView * mapView;
- (IBAction)setMap:(id)sender;
- (IBAction)getLocation:(id)sender;
#end
Map.m
#import "Map.h"
#import "Annotation.h"
#interface Map ()
#end
//define coordinates
#define Sofia_LATITUDE 42.745826;
#define Sofia_LONGITUDE 23.270186;
#define Plovdiv_LATITUDE 42.1333;
#define Plovdiv_LONGITUDE 24.75;
#define Varna_LATITUDE 43.2;
#define Varna_LONGITUDE 27.9167;
#define THE_SPAN 3.8;
#implementation Map
#synthesize mapView;
- (IBAction)getLocation:(id)sender {
mapView.showsUserLocation = YES;
[self.view addSubview:mapView];
}
- (IBAction)setMap:(id)sender {
switch (((UISegmentedControl *)sender).selectedSegmentIndex) {
case 0:
mapView.mapType = MKMapTypeStandard;
break;
case 1:
mapView.mapType = MKMapTypeSatellite;
break;
case 2:
mapView.mapType = MKMapTypeHybrid;
break;
default:
break;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
MKCoordinateRegion myRegion;
//Center the map
CLLocationCoordinate2D center;
center.latitude = 42.1333;
center.longitude = 24.75;
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
[mapView setRegion:myRegion animated:TRUE];
NSMutableArray * locations = [[NSMutableArray alloc]init];
CLLocationCoordinate2D location;
Annotation * myAnn;
//make annotations
myAnn = [[Annotation alloc]init];
location.latitude = Sofia_LATITUDE;
location.longitude = Sofia_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Милото";
myAnn.subtitle = #"Моята любов е ТУК!!!";
[locations addObject:myAnn];
myAnn = [[Annotation alloc]init];
location.latitude = Plovdiv_LATITUDE;
location.longitude = Plovdiv_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Plovdiv";
myAnn.subtitle = #"Plovdiv";
[locations addObject:myAnn];
myAnn = [[Annotation alloc]init];
location.latitude = Varna_LATITUDE;
location.longitude = Varna_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Varna";
myAnn.subtitle = #"Varna";
[locations addObject:myAnn];
[self.mapView addAnnotations:locations];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Annotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Annotation : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString * title;
#property (nonatomic, copy) NSString * subtitle;
#end
Annotation.m
#import "Annotation.h"
#implementation Annotation
#synthesize coordinate, title, subtitle;
#end
So when I launch the program and click the button to see the map, it appears but it is not centered. When I move back and again click to see the map everything is OK. Where is the problem?

You need to set the region for the mapview. The region has a coordinate (the middle) and a span (the numbers of the span stand for the degrees of the world that is shown on the map), play around with the span numbers to get the result you desire. You can set the region when you set your coordinate.
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
region.span = span;
region.center = self.coordinate;
[mapView setRegion:region animated:YES];

Related

MKAnnotation not displaying on map view

I am trying to create a custom annotation for a simple map view of mine, but the annotaiton pin is not showing up on the map when i run the simulator.
I have a MapViewAnnotation class which implements the MKAnnotation protocol, and I have another MapViewController class where I programmatically create a mapView and display the map.
MapViewAnnotation.h :
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MapViewAnnotation : NSObject <MKAnnotation>
#property (nonatomic, copy) NSString *title;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
-(id) initWithTitle: (NSString *) title AndCoordinate: (CLLocationCoordinate2D) coordinate;
#end
MapViewAnnotation.m :
#import "MapViewAnnotation.h"
#implementation MapViewAnnotation
#synthesize coordinate = _coordinate;
#synthesize title = _title;
-(id) initWithTitle:(NSString *)title AndCoordinate:(CLLocationCoordinate2D)coordinate{
self = [super init];
_title = title;
_coordinate = coordinate;
return self;
}
#end
MapViewController.h :
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface MapViewController : UIViewController
#property (weak, nonatomic) MKMapView *mapView;
-(void) goToLocation;
#end
MapViewController.m :
#import "MapViewController.h"
#import "MapViewAnnotation.h"
#define LATITUDE 42.3889;
#define LONGITUDE -72.5278;
#interface MapViewController ()
#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.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[self.view addSubview:self.mapView];
[self goToLocation];
[self.mapView addAnnotations:[self createAnnotations]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) goToLocation {
MKCoordinateRegion newRegion;
newRegion.center.latitude = LATITUDE;
newRegion.center.longitude = LONGITUDE;
newRegion.span.latitudeDelta = 0.05f;
newRegion.span.longitudeDelta = 0.05f;
self.mapView.showsPointsOfInterest = YES;
[self.mapView setRegion:newRegion animated:YES];
}
-(NSMutableArray *) createAnnotations {
NSMutableArray *annotations = [[NSMutableArray alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"location" ofType:#"plist"];
NSArray *locations = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *row in locations){
NSNumber *latitude = [row objectForKey:#"latitude"];
NSNumber *longitude = [row objectForKey:#"longitude"];
NSString *title = [row objectForKey:#"title"];
CLLocationCoordinate2D coord;
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
MapViewAnnotation *annotation = [[MapViewAnnotation alloc] initWithTitle:title AndCoordinate:coord];
[annotations addObject: annotation];
}
return annotations;
}
#end
I am taking am going through a plist where I have coordinates for one test location that I am trying to show on my map, but the pin is not displaying on the map. Again, I am doing this all programmatically, no xib, or storyboards (although that should not be the problem).
I do not know why the annotation is not showing up. I tried looking on stack for some other situations like mine but was unlucky to find anything that could help.
Thank you.
Answer was pretty simple,
In my plist I had the coordinates
latitude: 42.37
longitude: 72.536
when it should of actually been -72.536 for longitude.

Directions Issue in Map View

I am trying to provide directions to certain areas I have marked with map pins on my map view. On those pins I have displayed the name of the location and where it is located. I would like for them to be able to click the "i" that is usually on some Apple "pop ups" and it direct them to the Maps app and give them directions based on the coordinates I programmed in to place the map pin where it is. I will post two pictures first of what I have and what I would like to accomplish.
What I have right now
What I want to add to my pin (just the "i")
Now I will post my code of how I accomplished my first screenshot.
ViewController.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController
{
MKMapView *mapView;
}
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
-(IBAction)SetMap:(id)sender;
-(IBAction)GetLocation:(id)sender;
-(IBAction)Directions:(id)sender;
#end
ViewController.m:
#import "ViewController.h"
#import "MapPin.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
//Moss Preserve coordinates
MKCoordinateRegion MossPreserveRegion = { {0.0, 0.0}, {0.0, 0.0}};
MossPreserveRegion.center.latitude = 33.3816566;
MossPreserveRegion.center.longitude = -86.8415451;
MossPreserveRegion.span.longitudeDelta = 55.0;
MossPreserveRegion.span.latitudeDelta = 55.0;
[mapView setRegion:MossPreserveRegion animated:YES];
//Moss Preserve annotation and map pin
MapPin *MossPreserveAnnotation = [[MapPin alloc] init];
MossPreserveAnnotation.title = #"Moss Rock Preserve Boulder Fields";
MossPreserveAnnotation.subtitle = #"Hoover, AL";
MossPreserveAnnotation.coordinate = MossPreserveRegion.center;
[mapView addAnnotation:MossPreserveAnnotation];
//Horse Pens 40 coordinates
MKCoordinateRegion HorsePenRegion = { {0.0, 0.0}, {0.0, 0.0}};
HorsePenRegion.center.latitude = 33.9207535;
HorsePenRegion.center.longitude = -86.3089447;
HorsePenRegion.span.longitudeDelta = 55.0;
HorsePenRegion.span.latitudeDelta = 55.0;
[mapView setRegion:HorsePenRegion animated:YES];
//Horse Pens 40 annotation and map pin
MapPin *HorsePenAnnotation = [[MapPin alloc] init];
HorsePenAnnotation.title = #"Horse Pens 40";
HorsePenAnnotation.subtitle = #"Steele, AL ";
HorsePenAnnotation.coordinate = HorsePenRegion.center;
[mapView addAnnotation:HorsePenAnnotation];
// Create an MKMapItem to pass to the Maps app
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:MossPreserveAnnotation.coordinate
addressDictionary:nil];
MKMapItem *mossPreserveMapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mossPreserveMapItem setName:MossPreserveAnnotation.title];
NSDictionary *launchOptions = #{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
// Get the "Current User Location" MKMapItem
placemark = [[MKPlacemark alloc] initWithCoordinate:HorsePenRegion.coordinate
addressDictionary:nil];
MKMapItem *horsePenMapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
horsePenmapItem.name = HorsePenRegion.title;
// Pass the current location and destination map items to the Maps app
// Set the direction mode in the launchOptions dictionary
[MKMapItem openMapsWithItems:#[mossPreserveMapItem, horsePenmapItem]
launchOptions:launchOptions];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)SetMap:(id)sender;
{
switch (((UISegmentedControl *) sender).selectedSegmentIndex)
{
case 0:
mapView.mapType = MKMapTypeStandard;
break;
case 1:
mapView.mapType = MKMapTypeSatellite;
break;
case 2:
mapView.mapType = MKMapTypeHybrid;
break;
default:
break;
}
}
-(IBAction)GetLocation:(id)sender;
{
mapView.showsUserLocation = YES;
}
-(IBAction)Directions:(id)sender;
{
NSString *urlString = #"http://maps.apple.com/maps?daddr=33.3816566,-86.8415451";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}
#end
MapPin.h:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MapPin : NSObject <MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#end
MapPin.m:
#import "MapPin.h"
#implementation MapPin
#synthesize coordinate, title, subtitle;
#end
I see this all of the time in apps that I use. i just don't even really know what it is called, so I could even search for it. I am not looking for someone to hold my hand and tell me the answer, just some proper guidance and constructive criticism.
Thanks
Is this what you need?
#import "MapViewController.h"
#import "MapPin.h"
#import MapKit;
#interface MapViewController ()<MKMapViewDelegate>
#property (nonatomic, weak) IBOutlet MKMapView *mapView;
#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];
_mapView.delegate = self;
//Moss Preserve coordinates
MKCoordinateRegion MossPreserveRegion = { {0.0, 0.0}, {0.0, 0.0}};
MossPreserveRegion.center.latitude = 33.3816566;
MossPreserveRegion.center.longitude = -86.8415451;
MossPreserveRegion.span.longitudeDelta = 55.0;
MossPreserveRegion.span.latitudeDelta = 55.0;
[_mapView setRegion:MossPreserveRegion animated:YES];
//Moss Preserve annotation and map pin
MapPin *MossPreserveAnnotation = [[MapPin alloc] init];
MossPreserveAnnotation.title = #"Moss Rock Preserve Boulder Fields";
MossPreserveAnnotation.subtitle = #"Hoover, AL";
MossPreserveAnnotation.coordinate = MossPreserveRegion.center;
[_mapView addAnnotation:MossPreserveAnnotation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
// Create an MKMapItem to pass to the Maps app
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:view.annotation.coordinate
addressDictionary:nil];
MKMapItem *mossPreserveMapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mossPreserveMapItem setName:view.annotation.title];
NSDictionary *launchOptions = #{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
// Get the "Current User Location" MKMapItem
MKMapItem *currentLocationItem = [MKMapItem mapItemForCurrentLocation];
[MKMapItem openMapsWithItems:#[mossPreserveMapItem, currentLocationItem]
launchOptions:launchOptions];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:#"MKPinAnnotationView"];
annotationView.canShowCallout = YES;
UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
annotationView.rightCalloutAccessoryView = detailButton;
return annotationView;
}
You need to create 2 map items for your locations and pass as arguments to MKMapItem's openMapsWithItems:launchOptions:
// Create an MKMapItem to pass to the Maps app
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:MossPreserveAnnotation.coordinate
addressDictionary:nil];
MKMapItem *mapItem1 = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:MossPreserveAnnotation.title];
NSDictionary *launchOptions = #{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
// Get the "Current User Location" MKMapItem
placemark = [[MKPlacemark alloc] initWithCoordinate:HorsePenAnnotation.coordinate
addressDictionary:nil];
MKMapItem *mapItem2 = [[MKMapItem alloc] initWithPlacemark:placemark];
mapItem2.name = HorsePenAnnotation.title;
// Pass the current location and destination map items to the Maps app
// Set the direction mode in the launchOptions dictionary
[MKMapItem openMapsWithItems:#[mapItem1, mapItem2]
launchOptions:launchOptions];

Zooming to users location [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making this app where people can see what tourist attractions are near them and I'm a bit stuck!
I need it to load the user's current location when the app is loaded and zoom to it, however it's not doing so.
Sorry to be a bit blunt but I really don't know how to set it up so that it will work with both the button and load their location automatically.
https://pbs.twimg.com/media/BcRSTk0CAAEV47Q.jpg
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController{
MKMapView *mapview;
}
#property (weak, nonatomic) IBOutlet MKMapView *myMapView;
-(IBAction)getlocation;
#end
ViewController.m
#import "ViewController.h"
#import "Annotation.h"
#interface ViewController ()
#end
//Thorpe Park Coordinates
#define THORPE_LATITUDE 51.40395;
#define THORPE_LONGITUDE -0.51433;
//London Eye Coordinates
#define LONDONEYE_LATITUDE 51.50340;
#define LONDONEYE_LONGITUDE -0.11952;
//The New London Dungeons
#define LONDONDUGNEONS_LATITUDE 51.50231;
#define LONDONDUGNEONS_LONGITUDE -0.11965;
//Span
#define THE_SPAN 0.50f;
#implementation ViewController
#synthesize myMapView;
-(IBAction)getlocation {
mapview.showsUserLocation = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Create Region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = LONDONEYE_LATITUDE;
center.longitude = LONDONEYE_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
//Set our mapView
[myMapView setRegion:myRegion animated:YES];
//Annotation's
NSMutableArray * locations = [ [NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Annotation *myAnn;
//London Eye
myAnn = [[Annotation alloc] init];
location.latitude = LONDONEYE_LATITUDE;
location.longitude = LONDONEYE_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"The London Eye";
myAnn.subtitle = #"";
[locations addObject:myAnn];
//The New London Dungeons
myAnn = [[Annotation alloc] init];
location.latitude = LONDONDUGNEONS_LATITUDE;
location.longitude = LONDONDUGNEONS_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"The London Dungeons";
myAnn.subtitle = #"";
[locations addObject:myAnn];
//Thorpe Park
myAnn = [[Annotation alloc] init];
location.latitude = THORPE_LATITUDE;
location.longitude = THORPE_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Thorpe Park";
myAnn.subtitle = #"";
[locations addObject:myAnn];
[self.myMapView addAnnotations:locations];
/*
//1. Create a coordinate to be used with pin
CLLocationCoordinate2D ThorpeLocation;
ThorpeLocation.latitude = THORPE_LATITUDE;
ThorpeLocation.longitude = THORPE_LONGITUDE;
Annotation * myAnnotation = [Annotation alloc];
myAnnotation.coordinate = ThorpeLocation;
myAnnotation.title = #"Thorpe Park";
myAnnotation.subtitle = #"Theme Park";
[self.myMapView addAnnotation:myAnnotation];
*/
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Use this, and don't forget to put the delegate on your .h file, hope it works ;)
_mapView.userTrackingMode = YES;
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.00001;
span.longitudeDelta = 0.00001;
CLLocationCoordinate2D location = _mapView.userLocation.coordinate;
region.span = span;
region.center = location;
[_mapView setRegion:region animated:TRUE];
[_mapView regionThatFits:region];
}

show multiple annotation in map view

i am new to map view in ios sdk. i want to show multiple annotation in map view
using lat and long.basically all lat and long are coming from server side in
json format. i am parsing all lat and long and saving it in different array.
but how to show all annotation at single time. i am able to show only one annotation
at a time.Below is code for single annotation i am using,
zoomLocation.latitude = latmpa.doubleValue;
zoomLocation.longitude = logmpa.doubleValue;
annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = zoomLocation;
annotationPoint.title = #"masjid....";
[mapView selectAnnotation:annotationPoint animated:YES];
[mapView addAnnotation:annotationPoint];
mapView.centerCoordinate = annotationPoint.coordinate;
MKCoordinateSpan span;
span.latitudeDelta = 1.5;
span.longitudeDelta = 1.0;
MKCoordinateRegion newRegion;
newRegion.center = zoomLocation;
newRegion.span = span;
[mapView setRegion:newRegion animated:YES];
Try This
for ( int i=0; i<[yourLatLongarray count]; i++)
{
CLLocationCoordinate2D coord;
coord.latitude=[[NSString stringWithFormat:#"%#",[yourLatitudeArray objectAtIndex:i]] floatValue];
coord.longitude=[[NSString stringWithFormat:#"%#",
[yourLongitudeArray objectAtIndex:i]] floatValue];
MKCoordinateRegion region1;
region1.center=coord;
region1.span.longitudeDelta=20 ;
region1.span.latitudeDelta=20;
[mapview setRegion:region1 animated:YES];
NSString *titleStr =[namesArr objectAtIndex:i] ;
// NSLog(#"title is:%#",titleStr);
MyAnnotation* annotObj =[[MyAnnotation alloc]initWithCoordinate:coord title:titleStr];
[mapview addAnnotation:annotObj];
}
MyAnnotation.h is
#interface MyAnnotation : NSObject <MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subTitle;
NSString *time;
}
#property (nonatomic)CLLocationCoordinate2D coordinate;
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *subTitle;
#property (nonatomic,retain) NSString *time;
-(id)initWithCoordinate:(CLLocationCoordinate2D) c title:(NSString *) t subTitle:(NSString *)timed time:(NSString *)tim;
-(id)initWithCoordinate:(CLLocationCoordinate2D) c title:(NSString *)tit;
#end
MyAnnotation.m is
#implementation MyAnnotation
#synthesize coordinate;
#synthesize title;
#synthesize time;
#synthesize subTitle;
-(id)initWithCoordinate:(CLLocationCoordinate2D) c title:(NSString *) t subTitle:(NSString *)timed time:(NSString *)tim
{
self.coordinate=c;
self.time=tim;
self.subTitle=timed;
self.title=t;
return self;
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c title:(NSString *)tit
{
self.coordinate=c;
self.title=tit;
return self;
}
#end
Get all the latitudes and longitudes in array and go for the for loop as user1673099 said,
and add the following zoomtofit code for zooming the mapview to cover all the annotations in the mapview by calling the method,
[self zoomToFitMapAnnotations:self.mapView];
- (void)zoomToFitMapAnnotations:(MKMapView *)mapView {
if ([mapView.annotations count] == 0) return;
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for(id<MKAnnotation> annotation in mapView.annotations) {
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}

Multiple annotations from plist

I'm looking to adapt the following tutorial to create annotations from a plist. I'm brand new to Objective C and Xcode, and tried many different tutorials but can't seem to get this together.
Annotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Annotation : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString * title;
#property (nonatomic, copy) NSString * subtitle;
#property (nonatomic, copy) UIImageView * leftCalloutAccessoryView;
#end
Annotation.m
#import "Annotation.h"
#implementation Annotation
#synthesize coordinate, title, subtitle, leftCalloutAccessoryView;
#end
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet MKMapView *myMapView;
#end
ViewController.m
#import "ViewController.h"
#import "Annotation.h"
#interface ViewController ()
#end
//Wimbledon Coordinates
#define WIMB_LATITUDE 51.434783;
#define WIMB_LONGITUDE -0.213428;
//Stadium Coordinates
#define ARSENAL_LATITUDE 51.556899;
#define ARSENAL_LONGITUDE -0.106403;
#define CHELSEA_LATITUDE 51.481314;
#define CHELSEA_LONGITUDE -0.190129;
//Span
#define THE_SPAN 0.10f;
#implementation ViewController
#synthesize myMapView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Create the region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = ARSENAL_LATITUDE;
center.longitude = ARSENAL_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span=span;
//Set our mapView
[myMapView setRegion:myRegion animated:YES];
//Annotation
NSMutableArray * locations = [[NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Annotation * myAnn;
//Arsenal Annotation
myAnn = [[Annotation alloc] init];
location.latitude = ARSENAL_LATITUDE;
location.longitude = ARSENAL_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Arsenal FC";
myAnn.subtitle = #"The Gunners";
//myAnn.image = [UIImage imageNamed:#"location.png"];
[locations addObject:myAnn];
//Chelsea Annotation
myAnn = [[Annotation alloc] init];
location.latitude = CHELSEA_LATITUDE;
location.longitude = CHELSEA_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Chelsea FC";
myAnn.subtitle = #"The Blue Lions";
[locations addObject:myAnn];
[self.myMapView addAnnotations:locations];
}
//THIS CODE WORKS FOR CUSTOM ANNOTATIONS
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"redpin"];
newAnnotation.pinColor = MKPinAnnotationColorRed;
UIImageView *IconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker.png"]];
newAnnotation.leftCalloutAccessoryView = IconView;
newAnnotation.animatesDrop = YES;
newAnnotation.canShowCallout = YES;
return newAnnotation;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Got it to work thanks to a suggestion above. Also added in custom markers and a left icon to call out. I commented out the old coordinate code and the annotation red pins with left icon.
Hope this helps others who might've gone crazy searching for a solution as I have.
Stadiums.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Stadiums</key>
<array>
<dict>
<key>Title</key>
<string>Arsenal</string>
<key>Subtitle</key>
<string>The Gunners</string>
<key>Latitude</key>
<string>51.556899</string>
<key>Longitude</key>
<string>-0.106403</string>
</dict>
<dict>
<key>Title</key>
<string>Chelsea</string>
<key>Subtitle</key>
<string>The Blue Lions</string>
<key>Latitude</key>
<string>51.481314</string>
<key>Longitude</key>
<string>-0.190129</string>
</dict>
</array>
</dict>
</plist>
ViewController.m
#import "ViewController.h"
#import "Annotation.h"
#interface ViewController ()
#end
//Wimbledon Coordinates
#define WIMB_LATITUDE 51.434783;
#define WIMB_LONGITUDE -0.213428;
//Stadium Coordinates
#define ARSENAL_LATITUDE 51.556899;
#define ARSENAL_LONGITUDE -0.106403;
#define CHELSEA_LATITUDE 51.481314;
#define CHELSEA_LONGITUDE -0.190129;
//Span
#define THE_SPAN 0.10f;
#implementation ViewController
#synthesize myMapView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Create the region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = ARSENAL_LATITUDE;
center.longitude = ARSENAL_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span=span;
//Set our mapView
[myMapView setRegion:myRegion animated:YES];
/*
//Annotation
NSMutableArray * locations = [[NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Annotation * myAnn;
//Arsenal Annotation
myAnn = [[Annotation alloc] init];
location.latitude = ARSENAL_LATITUDE;
location.longitude = ARSENAL_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Arsenal FC";
myAnn.subtitle = #"The Gunners";
//myAnn.image = [UIImage imageNamed:#"location.png"];
[locations addObject:myAnn];
//Chelsea Annotation
myAnn = [[Annotation alloc] init];
location.latitude = CHELSEA_LATITUDE;
location.longitude = CHELSEA_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Chelsea FC";
myAnn.subtitle = #"The Blue Lions";
[locations addObject:myAnn];
[self.myMapView addAnnotations:locations];
*/
NSMutableArray *annotations = [[NSMutableArray alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Stadiums" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *anns = [dict objectForKey:#"Stadiums"];
NSLog(#"read1");
for(int i = 0; i < [anns count]; i++) {
NSLog(#"read2");
float realLatitude = [[[anns objectAtIndex:i] objectForKey:#"Latitude"] floatValue];
float realLongitude = [[[anns objectAtIndex:i] objectForKey:#"Longitude"] floatValue];
NSLog(#"read3");
Annotation *myAnnotation = [[Annotation alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [[anns objectAtIndex:i] objectForKey:#"Title"];
myAnnotation.subtitle = [[anns objectAtIndex:i] objectForKey:#"Subtitle"];
[myMapView addAnnotation:myAnnotation];
[annotations addObject:myAnnotation];
//[myAnnotation release];
}
}
//THIS CODE WORKS FOR CUSTOM ANNOTATIONS
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[myMapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil)
{
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
}
//Custom Pin
annotationView.image = [UIImage imageNamed:#"toilets.png"];
//Custom Thumbnail (left side)
UIImageView *IconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"toilets.png"]];
annotationView.leftCalloutAccessoryView = IconView;
annotationView.canShowCallout = YES;
annotationView.annotation = annotation;
return annotationView;
/*
MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"redpin"];
newAnnotation.pinColor = MKPinAnnotationColorRed;
UIImageView *ThumbView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"toilets.png"]];
newAnnotation.leftCalloutAccessoryView = ThumbView;
newAnnotation.animatesDrop = YES;
newAnnotation.canShowCallout = YES;
return newAnnotation;
*/
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Personally, I would use CoreData to store the annotations. However, if you are stuck on writing things to disk, I would make your annotation object implement the NSCoding protocol and use NSKeyedArchiver to save and load your objects.
+ (NSObject *)readArchiveFile:(NSString *)inFileName
{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectoryPath, inFileName];
NSObject *returnObject = nil;
if( [fileMgr fileExistsAtPath:filePath] )
{
#try
{
returnObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
#catch (NSException *exception)
{
[FileUtils deleteFile:inFileName];
returnObject = nil;
}
}
return returnObject;
}
+ (void)archiveFile:(NSString *)inFileName inObject:(NSObject *)inObject
{
NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectoryPath, inFileName];
#try
{
BOOL didSucceed = [NSKeyedArchiver archiveRootObject:inObject toFile:filePath];
if( !didSucceed )
{
NSLog(#"File %# write operation %#", inFileName, didSucceed ? #"success" : #"error" );
}
}
#catch (NSException *exception)
{
NSLog(#"File %# write operation threw an exception:%#", filePath, exception.reason);
}
}

Resources