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.
Related
I am primarily a JAVA programmer but took on a bus tracker project for the iPhone, so I am not very comfortable with this yet. Please forgive any noobish mistakes. The following code is how it was when I got pins to work. Any changes I made to attempt showing images has been removed.
#import "UICBus_FirstViewController.h"
#interface UICBus_FirstViewController ()
#end
#implementation UICBus_FirstViewController
#synthesize timer;
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 41.869271;
zoomLocation.longitude= -87.666436;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.85*METERS_PER_MILE, 0.85*METERS_PER_MILE);
// 3
MKCoordinateRegion adjustedRegion = [__mapView regionThatFits:viewRegion];
// 4
[__mapView setRegion:adjustedRegion animated:YES];
CGRect frame = self.view.bounds;
frame.size.height = frame.size.height - 40;
// Do any additional setup after loading the view, typically from a nib.
[self initRoutes];
timer = [NSTimer scheduledTimerWithTimeInterval: 5 target:self selector:#selector(updateLocations) userInfo:nil repeats: YES];
}
- (void)viewWillAppear:(BOOL)animated {
}
- (void)updateLocations {
[self updateBuses];
[self._mapView removeAnnotations:_Anns];
_Anns = [[NSMutableArray alloc] init];
for (int i = 0; i < _Buses.count; i++){
UICBus_Bus *Temp = _Buses[i];
CLLocationCoordinate2D ctrpoint;
ctrpoint.latitude = [Temp.getLat floatValue];
ctrpoint.longitude = [Temp.getLon floatValue];
MKAnnotation *addAnnotation = [[MKAnnotation alloc] initWithTitle:Temp.getMac andCoordinate:ctrpoint];
[_Anns addObject:addAnnotation];
}
[self._mapView addAnnotations:_Anns];
}
// ********************** Still need to add code to determine if bus is active or not **********************
- (void)updateBuses {
NSURL *url = [NSURL URLWithString:#"http://bus.uic.edu/api/latest"];
NSData *content = [NSData dataWithContentsOfURL:url];
NSError *JSONe;
_BusesInput = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&JSONe];
_Buses = [[NSMutableArray alloc] init];
UICBus_Bus *Temp;
if(_BusesInput.count < 1){
NSLog(#"No Buses Found/Empty JSON");
}else{
for (NSString* key in _BusesInput){
Temp = [[UICBus_Bus alloc] init:[_BusesInput objectForKey:key]];
[_Buses addObject:Temp];
}
}
}
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views{
MKAnnotationView *annotationView = [views objectAtIndex:0];
id <MKAnnotation> mp = [annotationView annotation];
[mv selectAnnotation:mp animated:YES];
}
- (void)viewDidUnload {
[self set_mapView:nil];
[super viewDidUnload];
}
#end
So, can I get this code to display a custom pin or do I need to rework it? and how?
You can directly work with didAddAnnotationViews method and didSelectAnnotation possibly while displaying and selecting custom image resp.
I found this link to help you best with How do I add custom pins to the iPhone MapKit?
Hope this helps.
-(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;
}
I am assigned to work with foursquare just recently. I have an app that needs to be authenticated and access the foursquare environment. I am having trouble with the following code to access checkins. I had already successfully made the authentication but the thing is that when I made a check in request, an errorType invalid_auth code 401 appears. I just don't know what's wrong with this.
Here is my full code; I am using fsq wrapper I found in github:
#import "FSQViewController.h"
#define kClientID #"XXXXXXXXXXXXXXXXXXXXXXX"
#define kCallbackURL #"invitation://foursquare"
#interface FSQViewController()
#property(nonatomic,readwrite,strong) BZFoursquare *foursquare;
#property(nonatomic,strong) BZFoursquareRequest *request;
#property(nonatomic,copy) NSDictionary *meta;
#property(nonatomic,copy) NSArray *notifications;
#property(nonatomic,copy) NSDictionary *response;
#end
#implementation FSQViewController
#synthesize foursquare = foursquare_;
#synthesize request = request_;
#synthesize meta = meta_;
#synthesize notifications = notifications_;
#synthesize response = response_;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.foursquare = [[BZFoursquare alloc]initWithClientID:kClientID callbackURL:kCallbackURL];
foursquare_.version = #"20120206";
foursquare_.locale = [[NSLocale currentLocale]objectForKey:NSLocaleLanguageCode];
foursquare_.sessionDelegate = (id<BZFoursquareSessionDelegate>) self;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark BZFoursquareRequestDelegate
- (void)requestDidFinishLoading:(BZFoursquareRequest *)request {
NSLog(#"test");
self.meta = request.meta;
self.notifications = request.notifications;
self.response = request.response;
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)request:(BZFoursquareRequest *)request didFailWithError:(NSError *)error {
NSLog(#"HERE > %s: %#", __PRETTY_FUNCTION__, error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[[error userInfo] objectForKey:#"errorDetail"] delegate:nil cancelButtonTitle:NSLocalizedString(#"OK", #"") otherButtonTitles:nil];
[alertView show];
self.meta = request.meta;
self.notifications = request.notifications;
self.response = request.response;
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
#pragma mark -
#pragma mark BZFoursquareSessionDelegate
- (void)foursquareDidAuthorize:(BZFoursquare *)foursquare {
NSLog(#"authorized!");
}
- (void)foursquareDidNotAuthorize:(BZFoursquare *)foursquare error:(NSDictionary *)errorInfo {
NSLog(#"not authorized! %s: %#", __PRETTY_FUNCTION__, errorInfo);
}
- (IBAction)click:(id)sender {
if (![foursquare_ isSessionValid]){
NSLog(#"here");
[foursquare_ startAuthorization];
} else {
[foursquare_ invalidateSession];
}
}
- (IBAction)checkin:(id)sender {
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"4d341a00306160fcf0fc6a88", #"venueId", #"public", #"broadcast", kClientID, #"oauth_token", nil];
self.request = [foursquare_ requestWithPath:#"checkins/add" HTTPMethod:#"POST" parameters:parameters delegate:self];
[request_ start];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
#end
can you help me guys? any help will highly be appreciated.
https://developer.foursquare.com/overview/responses
401 (Unauthorized) The OAuth token was provided but was invalid.
Might you have somehow corrupted your oauth token?
I am using the code below & it is working for me :
NSDictionary *parameters = #{#"venueId": #"4a0c6465f964a5202a751fe3", #"broadcast": #"public",#"oauth_token":kClientID};
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
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;
}