how to find the current location in iOS - ios

now i find the my current location in simulator
when press button show my current location
but my app located other locations
.h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
#property (nonatomic,retain)MKMapView *mapView;
- (IBAction)myview:(id)sender;
#property (strong, nonatomic) IBOutlet CLLocationManager *locationManger;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)myview:(id)sender {
_locationManger =[[CLLocationManager alloc]init];
_locationManger.distanceFilter=kCLDistanceFilterNone;
_locationManger.desiredAccuracy=kCLLocationAccuracyHundredMeters;
[_locationManger startUpdatingLocation];
[_mapView setMapType:MKMapTypeStandard];
[_mapView setZoomEnabled:YES];
[_mapView setScrollEnabled:YES];
MKCoordinateRegion region={ {0.0,0.0 },{0.0,0.0}};
region.center.latitude=_locationManger.location.coordinate.latitude;
region.center.longitude=_locationManger.location.coordinate.longitude;
region.span.longitudeDelta=0.007f;
region.span.latitudeDelta=0.007f;
[_mapView setRegion:region animated:YES];
[_mapView setDelegate:sender];
}
#end
i want when button press my current location show in map

use this following link it is very hopeful for you to find the current Location and etc, the link is http://www.appcoda.com/how-to-get-current-location-iphone-user/

Step 1: #import <MobileCoreServices/MobileCoreServices.h> in header file
Step 2: Add delegate CLLocationManagerDelegate
#interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to get location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSLog(#"placemark %#",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:#"%#, %#", Area,Country];
NSLog(#"%#",CountryArea);
}
else
{
NSLog(#"Geocode failed with error %#", error);
NSLog(#"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}

-(void)getLocationCurrentAddresslatitude:(NSString *)lat andlongitude:(NSString *)longitude
{
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?latlng=%#,%#&key=gfhhfhfhfghfghfhghfghfghDyk&result_type=street_address",lat,longitude];
NSLog(#"%#",jsonUrlString);
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSDictionary * rootDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSArray * result = [rootDictionary objectForKey:#"results"];
NSDictionary *dic=[result objectAtIndex:0];
NSString *address=[dic objectForKey:#"formatted_address"];
self.myAddress.text=address;
}

Related

Pass Data to another view controller

I have a two view controllers (DatePickerViewController and RouteHistoryViewController). I also have the server response in DatePickerViewController. How can I pass that response to the RouteHitoryViewController. The RouteHistoryViewController has a map view.
Here is the code DatePicker.m :
#import "DatePickerViewController.h"
#import "MapAnnotation.h"
#interface DatePickerViewController ()
#end
#implementation DatePickerViewController
{
//#define URL #"http://140e3087.ngrok.com"
#define URL3 #"http://784effb4.ngrok.com/bustracking/json/student/route_history"
NSString *formatedDate;
NSString *lat;
NSString *longi;
NSString *server_created_date;
}
#synthesize appDelagate,datePicker;
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"%#", appDelegate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
formatedDate = [dateFormatter stringFromDate:self.datePicker.date];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendPicker:(id)sender;
{
[self sendDataToServer : #"GET"];
// NSLog(#"%#", formatedDate);
//self.selectedDate.text =formatedDate;
}
-(void) sendDataToServer : (NSString *) method{
NSString *beaconiD = #"EC112729B51B";
NSString *trackerID = #"e61078a67e4233ad";//appDelagate.tracker_id;
NSString *date = formatedDate;
NSMutableURLRequest *request = nil;
NSString *getURL = [NSString stringWithFormat:#"%#?beacon_id=%#&tracker_id=%#&date=%#", URL3, beaconiD, trackerID, date];
getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"link: %#", getURL);
[request setHTTPMethod:#"GET"];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"connection: %#", connection);
if( connection )
{
mutData = [NSMutableData new];
}
else
{
NSLog (#"NO_CONNECTION");
return;
}
}
#pragma mark NSURLConnection delegates
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog (#"NO_CONNECTION");
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// NSString *jsonresultString =[jsonresultDict objectForKey:#"result"];
// NSLog(#"%#", jsonresultString);
// //serverResponse.text = jsonresultString;
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:mutData options:kNilOptions error:&error];
NSArray *fetchedArr = [json objectForKey:#"result"];
for (NSDictionary *user in fetchedArr)
{
lat = [user objectForKey:#"latitude"];
longi = [user objectForKey:#"longitude"];
server_created_date = [user objectForKey:#"server_created_date"];
NSLog(#"Item date&time : %#", server_created_date);
NSLog(#"Item longitude : %#", longi);
NSLog(#"Item latitude : %#", lat);
}
}
Here is the code RouteHistory.m:
#import "RouteHistoryViewController.h"
#import "MapAnnotation.h"
#interface RouteHistoryViewController ()
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#end
#implementation RouteHistoryViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
//[self.mapView removeAnnotations:self.mapView.annotations];
MapAnnotation *mapPoint = [[MapAnnotation alloc] init];
mapPoint.coordinate = CLLocationCoordinate2DMake([self.appDelagate.latitude doubleValue], [self.appDelagate.longitude doubleValue]);
mapPoint.title = self.appDelagate.name;
mapPoint.time = self.appDelagate.server_created_date;
mapPoint.mapimage = self.appDelagate.image;
// Add it to the map view
[self.mapView addAnnotation:mapPoint];
// Zoom to a region around the pin
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);
[self.mapView setRegion:region];
//testing
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveTestNotification:)
name:#"MapUpdate"
object:nil];
// Do any additional setup after loading the view.
}
#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *view = nil;
static NSString *reuseIdentifier = #"MapAnnotation";
// Return a MKPinAnnotationView with a simple accessory button
view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
if(!view)
{
view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
view.canShowCallout = YES;
view.animatesDrop = YES;
}
return view;
}
datepicker to route history using prepareforsegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier]isEqualToString:#"b"])
{
RouteHistoryViewController *rh = segue.destinationViewController;
NSLog(#"%#", rh);
}
}
In first view controller inside connectionDidFinishLoading after this line
NSArray *fetchedArr = [json objectForKey:#"result"];
add the following two lines
_responseFromServer = fetchedArr;
[self performSegueWithIdentifier:#"segueToRouteHistory" sender:self];
and then add this method in your first View Controller
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"segueToRouteHistory"])
{
RouteHistoryViewController *routeHistoryController = [segue segueToRouteHistory];
[routeHistoryController setFetchedArray:_responseFromServer];
}
}
In your First View Controller .h file add this
#property NSArray *responseFromServer;
Now We have assigned the Response array received from server to a object in your destination view controller.
Don't forget to add
#property NSArray *fetchedArray;
inside your Second ViewController's .h file
Now you can access this array in second view controller.
PS: Do not forget to give segue from storyboard from first view controller to second view controller and name the Segue Identifier as "segueToRouteHistory"

IOS 8 CLLocationManager Issue (Authorization Not Working)

#import "MyLocationViewController.h"
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#interface MyLocationViewController ()
#end
#implementation MyLocationViewController
{
CLLocationManager *locationManager;
}
- (void)requestAlwaysAuthorization
{
[locationManager requestAlwaysAuthorization];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.mapView.showsUserLocation = YES;
self.mapView.delegate = self;
locationManager = [[CLLocationManager alloc] init];
}
- (IBAction)unwindToMap:(UIStoryboardSegue *)segue
{
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.001;
mapRegion.span.longitudeDelta = 0.001;
CLLocationCoordinate2D location = userLocation.coordinate;
float lat = location.latitude;
float lng = location.longitude;
NSDictionary *locationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:lat] , #"Latitude",
[NSNumber numberWithFloat:lng], #"Longitude", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
locationDictionary, #"Location_A",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
if (mapView.userLocation != nil)
{
_longitudeLabel.text = [NSString stringWithFormat:#"%.8f", mapView.userLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", mapView.userLocation.coordinate.latitude];
}
[mapView setRegion:mapRegion animated: YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This is my code.
Now, I understand that I needed to edit my info.plist file (which I did) with a NSLocationAlwaysUsageDescription key, and I added a string for the description.
However, I'm having issues implementing the authorization portion, as the error still reads as such:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
I've read the Apple IOS 8 docs for the CLLocationManager, but somehow my code will not work.
Can someone help me so that the above error message goes away by looking at where in my code I need to modify so that it works?
Thanks!
You should not turn on MKMapView's showsUserLocation before the user has authorised your app to use Location services.
You can implement CLLocationManagerDelegate's locationManager:didChangeAuthorizationStatus: method and turn on showsUserLocation there like so:
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
self.mapView.showsUserLocation = YES;
}
}

Why is my first reponse null?

I have a Location.m model, which I use to obtain latitude and longitude. When I have those, I call my delegate method which is implemented in my Foursquare.m model.
Location.h looks like this:
#class Location;
#protocol LocationDelegate <NSObject>
- (void)location:(Location *)loc didFinishFindingLocation:(CLLocation *)location;
#end
#interface Location : NSObject <CLLocationManagerDelegate>
#property (nonatomic, weak) id <LocationDelegate> delegate;
- (void)startLocationManager;
#end
Location.m:
#implementation Location
{
CLLocationManager *_locationManager;
BOOL _locationIsUpdated;
}
- (void)startLocationManager
{
NSLog(#"In startLocationManager");
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
_locationManager.delegate = self;
_locationIsUpdated = NO;
[_locationManager startUpdatingLocation];
}
#pragma mark - LocationManager Delegates
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if (locations && _locationIsUpdated == NO) {
self.location = [locations lastObject];
NSLog(#"%#", _location);
_locationIsUpdated = YES;
[self.delegate location:self didFinishFindingLocation:self.location];
}
}
#end
When the delegate method is called from the Foursquare model, and I NSLog out the response in an array (called self.dataResponse). It always outputs (null) first, then all the JSON. Why does that happen? If I NSLog out dataDictionary (see code below) directly, the JSON output shows a error-code:400 and nothing is printed. Couple of milliseconds after everything is printed and seems to be working fine...
Here is a picture:
When I log the dataDictionary
Here is the delegate method implemented in Foursquare.m:
- (void)location:(Location *)loc didFinishFindingLocation:(CLLocation *)location
{
loc.delegate = self;
self.resultFromResponse = [[NSMutableArray alloc] init];
NSString *search = [NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?ll=%f,%f&radius=2000&categoryId=4d4b7105d754a06374d81259&client_id=%#&client_secret=%#&v=%#", location.coordinate.latitude, location.coordinate.longitude, kFourdquareAPIKey, fFoursquareSecret, [Foursquare getCurrentDate]];
NSURL *url = [NSURL URLWithString:search];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *dataDictionary = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!error) {
self.dataResponse = dataDictionary[#"response"][#"venues"];
NSLog(#"%#", self.dataResponse);
for (NSDictionary *venue in self.dataResponse) {
FSDataFromJSON *data = [[FSDataFromJSON alloc] init];
data.name = venue[#"name"];
data.phone = venue[#"phone"];
data.location = venue[#"location"];
[self.resultFromResponse addObject:data];
}
//[[NSNotificationCenter defaultCenter] postNotificationName:#"JSONRequestFinishedLoading" object:nil];
} else {
NSLog(#"%#", error.description);
}
}];
[task resume];
}
At the very end, these models is started in my MainViewController:
_location = [[Location alloc] init];
[_location startLocationManager];
_foursquare = [[Foursquare alloc] init];
[_foursquare location:_location didFinishFindingLocation:_location.location];
From what I can tell, the last line of code in your question is likely the problem:
[_foursquare location:_location didFinishFindingLocation:_location.location];
You shouldn't be calling your delegate method explicitly (before the location has been set). Instead, you should be waiting for the CLLocation callback to kick it off.
Other thoughts:
If the Location class has a .location property, I think that's confusing.
Location.m is not a model, it's the file containing the class implementation. I'd say the Location class is a model.
You could simplify your delegate method as didFindLocation:(Location *)location since you can get the CLLocation in the method as location.location.
What are the three most important factors in real estate? location.location.location!

How to get current location using CLLocationManager in iOS

I can already find the current location using latitude and longitude, but I would also like to be able to find the current location given a zip code.
Here is what I have so far:
.h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
IBOutlet UILabel *label1;
IBOutlet UILabel *lable2;
}
#property (weak, nonatomic) IBOutlet MKMapView *myMapview;
#property (weak, nonatomic) IBOutlet UILabel *label2;
#property (weak, nonatomic) IBOutlet UILabel *lable1;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
_myMapview.showsUserLocation = YES;
[self->locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
//NSLog(#”dLatitude : %#”, latitude);
//NSLog(#”dLongitude : %#”,longitude);
NSLog(#"MY HOME :%#", latitude);
NSLog(#"MY HOME: %# ", longitude);
}
#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
[self->locationManager stopUpdatingLocation];
NSLog(#"my latitude :%f",currentLocation.coordinate.latitude);
NSLog(#"my longitude :%f",currentLocation.coordinate.longitude);
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSLog(#"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error)
{
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"Monday");
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark.ISOcountryCode %#",placemark.ISOcountryCode);
}];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil)
{
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Step 1: Import MobileCoreServices framework in .h File
#import <MobileCoreServices/MobileCoreServices.h>
Step 2: Add delegate CLLocationManagerDelegate
#interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to get location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSLog(#"placemark %#",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:#"%#, %#", Area,Country];
NSLog(#"%#",CountryArea);
}
else
{
NSLog(#"Geocode failed with error %#", error);
NSLog(#"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
Here is a code to get user current location using block
1) #import <CoreLocation/CoreLocation.h>
2) <CLLocationManagerDelegate>
3) in .h file
//Location
typedef void(^locationBlock)();
//Location
-(void)GetCurrentLocation_WithBlock:(void(^)())block;
#property (nonatomic, strong) locationBlock _locationBlock;
#property (nonatomic,copy)CLLocationManager *locationManager;
#property (nonatomic)CLLocationCoordinate2D coordinate;
#property (nonatomic,strong) NSString *current_Lat;
#property (nonatomic,strong) NSString *current_Long;
4) in .m file
#pragma mark - CLLocationManager
-(void)GetCurrentLocation_WithBlock:(void(^)())block {
self._locationBlock = block;
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLDistanceFilterNone];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
if (IS_OS_8_OR_LATER) {
if ([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];
}
}
[_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLoc=[locations objectAtIndex:0];
_coordinate=currentLoc.coordinate;
_current_Lat = [NSString stringWithFormat:#"%f",currentLoc.coordinate.latitude];
_current_Long = [NSString stringWithFormat:#"%f",currentLoc.coordinate.longitude];
NSLog(#"here lat %# and here long %#",_current_Lat,_current_Long);
self._locationBlock();
[_locationManager stopUpdatingLocation];
_locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
}
5) Call function
- (void)viewDidLoad {
[super viewDidLoad];
[self GetCurrentLocation_WithBlock:^{
NSLog(#"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]);
}];
}
6) And add below line to .plist
Any one or both of below keys needs to be added in Info.plist file.
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
if location permissions not asking when you first launch then you cant get your current location .
iOS8 has got us major API changes with the LocationsServices
Assuming [CLLocationManager locationServicesEnabled] return YES,
With the First Launch of the iOS App [both iOS7 and iOS8] - locationMangers(CLLocationManager)
You can call Google APIs Maps service to get the location using zipcode:
Just enter your zipcode in address={your zipcode}.

How to make Google Maps link with location data in iOS

I have the latitude & Longitude data of a location, how can I make it a Google Maps link, when the user clicks on share and choose option like email.
Here is the code that I use to get location data:
// Here is the .h file
#interface locate : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>
{
CGPoint gestureStartPoint;
CLLocationManager *locationManager;
CLLocation *startingPoint;
UILabel *latitudeLabel;
UILabel *longitudeLabel;
UILabel *altitudeLabel;
MKMapView *mapView;
}
#property (assign) CGPoint gestureStartPoint;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, retain) CLLocation *startingPoint;
#property (nonatomic, retain) IBOutlet UILabel *latitudeLabel;
#property (nonatomic, retain) IBOutlet UILabel *longitudeLabel;
#property (nonatomic, retain) IBOutlet UILabel *altitudeLabel;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#end
// Here is the .m file
#import "locate.h"
#implementation locate
#synthesize gestureStartPoint,locationManager,startingPoint,latitudeLabel,longitudeLabel,altitudeLabel,mapView;
- (void)dealloc
{
[locationManager release];
[startingPoint release];
[latitudeLabel release];
[longitudeLabel release];
[altitudeLabel release];
[super dealloc];
}
- (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
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
if (startingPoint == nil)
self.startingPoint = newLocation;
NSString *latitudeString = [[NSString alloc] initWithFormat:#"%g\u00B0",
newLocation.coordinate.latitude];
latitudeLabel.text = latitudeString;
[latitudeString release];
NSString *longitudeString = [[NSString alloc] initWithFormat:#"%g\u00B0",
newLocation.coordinate.longitude];
longitudeLabel.text = longitudeString;
[longitudeString release];
NSString *altitudeString = [[NSString alloc] initWithFormat:#"%gm",
newLocation.altitude];
altitudeLabel.text = altitudeString;
[altitudeString release];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSString *errorType = (error.code == kCLErrorDenied) ?
#"Access Denied" : #"Unknown Error";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error getting Location"
message:errorType
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)viewDidLoad
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
mapView.delegate = self;
mapView.mapType = MKMapTypeStandard;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.locationManager = nil;
self.latitudeLabel = nil;
self.longitudeLabel = nil;
self.altitudeLabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#end
Now please someone help me on how can I use the location data to create Google Maps link?
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[txtf_mapsearch.text 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;
You need this code.
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/maps?q=%1.6f,%1.6f",
newLocation.coordinate.latitude,
newLocation.coordinate.longitude];
linkMap.text = googleMapsURLString;
Try this
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",
self.currentLocation.coordinate.latitude,
self.currentLocation.coordinate.longitude,
longitude,
latitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapsURLString]];
where latitude and longitude are the point of interest.

Resources