Get the address of current user location - iphone

I follow some tutorial and mix my awful code. Now I can get my current location. And when I tap on a button it will trigger a pin which locates on my current location. If I tap on the pin, the message shows address of my current.
I have two question:
Why I can not get a more precise address? Now I receive address with country, city and district, but without name of the road.
How can I get the "text" of the address of current location? I want to display the address in a UILabel elsewhere but don't know how to do that.
Thank you very much!
here's the .h
#import <UIKit/UIKit.h>
#import "MapKit/MapKit.h"
#import "CoreLocation/CoreLocation.h"
#interface UserLocationAddressViewController : UIViewController <MKMapViewDelegate,MKReverseGeocoderDelegate>
{
MKMapView *userLocationAddMapView;
CLLocationManager *locationManager;
}
#property (nonatomic, retain) MKMapView *userLocationAddMapView;
-(IBAction)getUserLocationAddress:(id)sender;
#end
And Here's .m
#import "UserLocationAddressViewController.h"
#implementation UserLocationAddressViewController
#synthesize userLocationAddMapView;
-(IBAction)getUserLocationAddress:(id)sender
{
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:locationManager.location.coordinate];
geoCoder.delegate = self;
[geoCoder start];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)dealloc
{
[userLocationAddMapView release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.userLocationAddMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
userLocationAddMapView.showsUserLocation = YES;
userLocationAddMapView.delegate = self;
self.userLocationAddMapView.mapType = MKMapTypeStandard;
locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
CLLocationCoordinate2D coordinate = locationManager.location.coordinate;
MKCoordinateRegion mapRegion;
mapRegion.center = coordinate;
MKCoordinateSpan mapSpan;
mapSpan.latitudeDelta = 0.006;
mapSpan.longitudeDelta = 0.006;
mapRegion.span = mapSpan;
[userLocationAddMapView setRegion:mapRegion animated:YES];
self.userLocationAddMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.userLocationAddMapView];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:#"Get Add" style:UIBarButtonItemStylePlain target:self action:#selector(getUserLocationAddress:)] autorelease];
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSLog(#"placemark %f %f", placemark.coordinate.latitude, placemark.coordinate.longitude);
NSLog(#"addressDictionary %#", placemark.addressDictionary);
[userLocationAddMapView addAnnotations:[NSArray arrayWithObjects:placemark, nil]];
[geocoder release];
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"reverseGeocoder fail");
[geocoder release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end

You shouldn't really use MKReverseGeocoder as it has been depreciated by apple in iOS5, you should really use CLGeocoder. The following example will return a whole tonne of information which is based in the NSArray *placemarks, you can then iterate through them and call the keys in the assoc array.
#import "MapPoint.h"
#implementation MapPoint
#synthesize coordinate, title, dateAdded, subtitle, city, reverseGeo;
-(id)initWithCoordinates:(CLLocationCoordinate2D)c
title:(NSString *)t {
self = [super init];
if (self) {
coordinate = c;
[self setTitle: t];
[self setCurrentCity: [[CLLocation alloc] initWithLatitude:c.latitude longitude:c.longitude]];
[self setDateAdded: [[NSDate alloc] init]];
}
return self;
}
-(void)setCurrentCity: (CLLocation *)loc {
if (!self.reverseGeo) {
self.reverseGeo = [[CLGeocoder alloc] init];
}
[self.reverseGeo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [formatter stringFromDate: [self dateAdded]];
[self setSubtitle: [dateString stringByAppendingString: [placemark locality] ] ];
}
}];
}
#end

Just place this delegate methods, I hope this may help you.
-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
NSLog(#"MKReverseGeocoder has failed.");
}
-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
currentLocation = [placemark.locality stringByAppendingFormat:#", "];
currentLocation = [currentLocation stringByAppendingString:placemark.country];
[indicator stopAnimating];
txtLocation.text = currentLocation;
}

I have got the same issue, MKReverseGeocoder doesn't always return the full address, beacause sometimes the coordinates is not accurate enough and the service can't generate an approximative address.
In order to get best results i have implemented an other reverse geocoding against yahoo. So basically if MKReverseGeocoder (google) doesn't return a full address, i query yahoo who can generate an approximative one.
On the other hand be carreful with MKReverseGeocoder it has been deprecated in IOS 5, they recommand to use CLGeocoder instead

Related

(MKAnnotationView *) mapView: not firing on first view

-(MKAnnotationView *) mapView: is not firing on the first run of the view.
I load pins in from a JSON call. The pins load fine with all the information but the call out(*see code) and turning them purple.(done in the -(MKAnnotationView *) mapView2:) however when I leave that tab and go back to it then it gets called and all is well.
Why this in not OK? Because end-users will not know that the map pins have a call out with phone call capabilities if they only check once.
Progress Flow: it loads the map. Loads the Pins. Changes the pins to purple with the call out. Then Zooms to pins and current location. But on the first run it does not Change the pins with call out.
I have narrowed it down to -(MKAnnotationView *) mapView: not firing the first time on several tests however on one test it did fire but only was called on the second of two pins till the view was reloaded.
I am open to any suggestions to improve any of the code weather it pertains to this or not. I always love learning better ways to do what I have done. So feel free with your criticisms.
.h file
#class Reachability;
#interface LocationsViewController : UIViewController <MKMapViewDelegate,CLLocationManagerDelegate>
{
NSString *phone;
IBOutlet MKMapView *mapView;
CLLocationManager *locationManager;
NSURLConnection *theConnection;
Reachability* internetReachable;
Reachability* hostReachable;
}
#property(nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic, retain)CLLocationManager *locationManager;
#property(nonatomic, retain) NSString *phone;
- (BOOL) connectedToNetwork;
- (void) mapPinsJSON;
#end
.m file
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
MapAnnotation *ann1;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
MKCoordinateRegion region;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
NSTimer *myTimer;
myTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(countDown) userInfo:nil repeats:NO];
[self zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
-(void)countDown{
[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[mapView removeAnnotations:mapView.annotations];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[self performSelectorInBackground:#selector(mapPinsJSON) withObject:nil];
}
}
- (void) mapPinsJSON{
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/api/newlocations25/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#define MINIMUM_ZOOM_ARC 0.014 //approximately 1 miles (1 degree of arc ~= 69 miles)
#define ANNOTATION_REGION_PAD_FACTOR 1.15
#define MAX_DEGREES_ARC 360
- (void)zoomMapViewToFitAnnotations:(MKMapView *)mapView3 animated:(BOOL)animated
{
NSArray *annotations = mapView.annotations;
int count = [mapView.annotations count];
if ( count == 0) { return; } //bail if no annotations
//convert NSArray of id <MKAnnotation> into an MKCoordinateRegion that can be used to set the map size
//can't use NSArray with MKMapPoint because MKMapPoint is not an id
MKMapPoint points[count]; //C array of MKMapPoint struct
for( int i=0; i<count; i++ ) //load points C array by converting coordinates to points
{
CLLocationCoordinate2D coordinate = [(id <MKAnnotation>)[annotations objectAtIndex:i] coordinate];
points[i] = MKMapPointForCoordinate(coordinate);
}
//create MKMapRect from array of MKMapPoint
MKMapRect mapRect = [[MKPolygon polygonWithPoints:points count:count] boundingMapRect];
//convert MKCoordinateRegion from MKMapRect
MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
//add padding so pins aren't scrunched on the edges
region.span.latitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;
region.span.longitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;
//but padding can't be bigger than the world
if( region.span.latitudeDelta > MAX_DEGREES_ARC ) { region.span.latitudeDelta = MAX_DEGREES_ARC; }
if( region.span.longitudeDelta > MAX_DEGREES_ARC ){ region.span.longitudeDelta = MAX_DEGREES_ARC; }
//and don't zoom in stupid-close on small samples
if( region.span.latitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.latitudeDelta = MINIMUM_ZOOM_ARC; }
if( region.span.longitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.longitudeDelta = MINIMUM_ZOOM_ARC; }
//and if there is a sample of 1 we want the max zoom-in instead of max zoom-out
if( count == 1 )
{
region.span.latitudeDelta = MINIMUM_ZOOM_ARC;
region.span.longitudeDelta = MINIMUM_ZOOM_ARC;
}
[mapView3 setRegion:region animated:animated];
}
#end
Well I feel sheepish. Here is what fixed it for me.
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
}

How do I set map zoom based on nearest pin to current location

Right now I am setting my region based on users current location. I would like to now set the zoom level so I can see the users current location and the nearest pin that is being pulled in via json.
Not until run time will the app know the number of pins or the locations of said pins.
Here is what I have so far.
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"New latitude: %f", newLocation.coordinate.latitude);
NSLog(#"New longitude: %f", newLocation.coordinate.longitude);
MKCoordinateRegion region;
region.center.latitude =newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
//[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[mapView removeAnnotations:mapView.annotations];
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I did something similar, but based on two annotations, not the user's location. You should be able to replace mapView.centerCoordinate with mapView.userLocation.coordinate.
in viewForAnnotation:
CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
Note, this code will re-calc the zoom level each time you add an annotation. You may need to save the distance and only change the map if the new distance is greater than the prior distance.

CoreLocation Framework Issues

I have used Core location framework to receive my GPS coordinates in my IPOD.First time i can get the Latitude and longitude, then i got an error message , kCLErrorDomain Code=0 Operation Could not be completed.
But the error message never change.I think first time only it works
This is My code
#import "CoreLocationDemoViewController.h"
#implementation CoreLocationDemoViewController
#synthesize CLController;
- (void)viewDidLoad {
[super viewDidLoad];
CLController = [[CoreLocationController alloc] init];
CLController.delegate = self;
[CLController.locMgr startUpdatingLocation];
}
- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:#"SPEED: %f", [location speed]];
latitudeLabel.text = [NSString stringWithFormat:#"LATITUDE: %f", location.coordinate.latitude];
longitudeLabel.text = [NSString stringWithFormat:#"LONGITUDE: %f", location.coordinate.longitude];
altitudeLabel.text = [NSString stringWithFormat:#"ALTITUDE: %f", [location altitude]];
errorLabel.text = #"";
}
- (void)locationError:(NSError *)error {
if(!CLController) //.text )
{
errorLabel.text = [error description];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return YES;
}
- (void)viewDidUnload {
}
- (void)dealloc {
[CLController release];
[super dealloc];
}
#end
Anybody know what are the issues, help is highly appreciated.
Thanks,
VKS
Yes iPod doesn't have GPS functionality. Test your app either in simulator or iPhone not on iPod.

Need to get current location and destination location pin

How do I get the current location with green pin and destination location with red pin?
When I work on some stuff I get only destination location with red pin, not at the current location.
My source code.
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import <CoreLocation/CoreLocation.h>
#interface AddressAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
// CLLocationManager *locationManager;
// CLLocation *currentLocation;
}
#end
#interface MapViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate> {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
NSString *address;
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
#property(nonatomic,retain)CLLocation *currentLocation;
#property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
#end
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return #"Event";
}
- (NSString *)title{
//return #"Title";
return #"Allure-Exclusive";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES;
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title=#"Map-View";
// [self addressLocation];
[self showAddress];
NSLog(#"address is %#",address);
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.5;
span.longitudeDelta=0.5;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(#"locationString %#",locationString);
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
NSLog(#"listItems %#",[listItems objectAtIndex:2]);
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation) {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
//
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// [self stop];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[super dealloc];
}
#end
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation)
{
mapView.userLocation.title=#"Current Location";
[mapView setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
return nil;
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
When I changed the method. it's pointing blue and blinking,but it was pointing at different location, which is at infinite Loop mariani Ave location.
It was running this in a simulator.
You'll want to set showsUserLocation.
mapView.showsUserLocation = YES;

need to drop pin at two places... current location and events locations

I need help on this .... drop the pins.
current location.... pin drop.... with blue....
Event location :locations latitude:53.373812...longitude 4.890951 with red pin.
I did like this:
#interface AddressAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
// CLLocationManager *locationManager;
// CLLocation *currentLocation;
}
#end
#interface MapViewController : UIViewController <CLLocationManagerDelegate> {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
NSString *address;
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
#property(nonatomic,retain)CLLocation *currentLocation;
#property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
#end
//Implementation file.
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return #"Event";
}
- (NSString *)title{
//return #"Title";
return #"Location ";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
[locationManager startUpdatingLocation];
}
-(void)stop{
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title=#"Map-View";
[self addressLocation];
[self showAddress];
NSLog(#"address is %#",address);
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[super dealloc];
}
#end
Please help me out...
thanks in adavance.
Showing user current location is simple.
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES; //This will show the current location as blue dot in your mapview
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
In your viewForAnnotation Delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if (annotation == mapView.userLocation)
{
// This code will execute when the current location is called.
return nil;
}
else
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}