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.
Related
This is my first post every here. Woohoo.
Here is my story ... I spent about a week trying tutorials about geofencing in IOS. The problem is that i have to do it in Objective-C for now.
I am trying to get a small app to run this geofencing but i keep having problems with the actual trigger events.
I am testing it on my actual phone (iPhone 7Plus) and i can't get to make some events show on the screen whether i'm inside the region or out.
i will paste code from the .h and .m files. these are the only ones that i have implemented so far.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *myLat;
#property (weak, nonatomic) IBOutlet UILabel *myLon;
#property (weak, nonatomic) IBOutlet UILabel *destLat;
#property (weak, nonatomic) IBOutlet UILabel *destLon;
#property (weak, nonatomic) IBOutlet UILabel *diff;
#property (weak, nonatomic) IBOutlet UILabel *answer;
#property BOOL alwaysOn;
#property BOOL isCLickOn;
#property (retain, nonatomic) CLLocationManager *locationManager;
#end
... and this what i have in my .m file:
#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) viewDidAppear:(BOOL)animated{
// [self showAlertMessage:#"Test" message:#"Maybe works"];
// [self showAlertMessage:#"Test" message:#"Maybe works"];
[self setupTheAuthorizations];
if(!_isCLickOn){
[self startTheRegionMonitoring];
}
// _answer.text = #"Merge";
}
- (void) setupTheAuthorizations {
_locationManager = [[CLLocationManager alloc] init];
[_locationManager requestAlwaysAuthorization];
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
//check the type of authorization
CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
switch (authStatus) {
case kCLAuthorizationStatusAuthorizedAlways:
// should do somethinglike getting the things started and stuff like that ...
_alwaysOn = YES;
break;
case kCLAuthorizationStatusNotDetermined:
[_locationManager requestAlwaysAuthorization];
default:
break;
}
}
- (void) startTheRegionMonitoring {
if (_alwaysOn && [CLLocationManager isMonitoringAvailableForClass:[CLRegion class]]){
CLLocationDegrees latitude = 37.972004;
CLLocationDegrees longitude = -121.293740;
CLLocationDistance radius = 200;
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center radius:radius identifier:#"CH"];
region.notifyOnEntry = YES;
region.notifyOnExit = YES;
_destLat.text = [NSString stringWithFormat:#"%f", latitude];
_destLon.text = [NSString stringWithFormat:#"%f", longitude];
_myLat.text = [NSString stringWithFormat:#"%f", _locationManager.location.coordinate.latitude];
_myLon.text = [NSString stringWithFormat:#"%f", _locationManager.location.coordinate.longitude];
[_locationManager startMonitoringForRegion:region];
}
_isCLickOn = YES;
}
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
}
- (void)locationManager:(CLLocationManager *)manager
didEnterRegion:(CLRegion *)region{
NSLog(#"entered region");
if ([region.identifier isEqualToString:#"CH"]){
_answer.text = #"IN";
CLLocation *me = [[CLLocation alloc] initWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude];
CLLocation *dest = [[CLLocation alloc] initWithLatitude:37.972004
longitude:-121.293740];
int dist = [me distanceFromLocation:dest];
_diff.text = [NSString stringWithFormat:#"%i", dist];
}
}
- (void)locationManager:(CLLocationManager *)manager
didExitRegion:(CLRegion *)region{
NSLog(#"entered region");
if ([region.identifier isEqualToString:#"CH"]) {
_answer.text = #"OUT";
CLLocation *me = [[CLLocation alloc] initWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude];
CLLocation *dest = [[CLLocation alloc] initWithLatitude:37.972004
longitude:-121.293740];
int dist = [me distanceFromLocation:dest];
_diff.text = [NSString stringWithFormat:#"%i", dist];
}
}
- (void)locationManager:(CLLocationManager *)manager
didStartMonitoringForRegion:(CLRegion *)region __OSX_AVAILABLE_STARTING(__MAC_10_8,__IPHONE_5_0) __TVOS_PROHIBITED __WATCHOS_PROHIBITED{
NSLog(#"Monitoring started");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"error");
}
- (void) showAlertMessage:(NSString *)title message:(NSString *)message {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
What happens is that i don't get any events showing on my phone even when the app is open. so I have a view controller on the storyboard that is supposed to show my location and destination location and to show the distance between the two objects. But it doesn't show it even if i walk 400 meters and then i walk back to the center.
I know that Swift is what I should use, and I will switch to Swift but for right now I am really wanting to understand the process that goes in this geofencing thing.
Any help will be appreciated. I am also pretty new at programming so I still have things that I am trying to learn and understand about Objective-C in particular.
Thank you.
At the most recent Google IO, they released the Google Places API for iOS. I'm having trouble, though, when the location used to pick places isn't hard coded. I want to find places nearby with the Place Picker.
Here's a screenshot of how the current location isn't picked up:
Here's my code:
FirstViewController.h:
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
#import <CoreLocation/CoreLocation.h>
#interface FirstViewController : UIViewController
//<GMSMapViewDelegate>
#property (nonatomic,retain) CLLocationManager *locationManager;
#property (strong, nonatomic) NSString *name2;
#property (strong, nonatomic) NSString *address2;
#property (strong, nonatomic) NSString *cat;
//#property (strong, nonatomic) NSString *lat;
//#property (strong, nonatomic) NSString *lon;
//
#property double latitude;
#property double longitude;
#property (weak, nonatomic) IBOutlet UILabel *nameLabel;
#property (weak, nonatomic) IBOutlet UILabel *addressLabel;
#property (weak, nonatomic) IBOutlet UILabel *catLabel;
#end
FirstViewController.m:
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController {
GMSPlacePicker *_placePicker;
GMSMapView *mapView_;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
// locationManager.delegate = self; // we set the delegate of locationManager to self.
// locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
// [locationManager requestAlwaysAuthorization];
//
// [locationManager startUpdatingLocation]; //requesting location updates
mapView_.settings.myLocationButton = YES;
mapView_.myLocationEnabled = YES;
mapView_.hidden = YES;
NSLog(#"User's location: %#", mapView_.myLocation);
}
//
//-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
// UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an error retrieving your location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// [errorAlert show];
// NSLog(#"Error: %#",error.description);
//}
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//{
// CLLocation *crnLoc = [locations lastObject];
// _lat = [NSString stringWithFormat:#"%.8f",crnLoc.coordinate.latitude];
// _lon = [NSString stringWithFormat:#"%.8f",crnLoc.coordinate.longitude];
// double _latitude = [_lat doubleValue];
// double _longitude = [_lon doubleValue];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//- (NSString *)deviceLocation
//{
// NSString *theLocation = [NSString stringWithFormat:#"%f, %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
// return theLocation;
//}
// Add a UIButton in Interface Builder to call this function
- (IBAction)pickPlace:(UIButton *)sender {
CLLocation *myLocation = mapView_.myLocation;
// CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.788204, -122.411937);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(center.latitude + 0.001,
center.longitude + 0.001);
CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(center.latitude - 0.001,
center.longitude - 0.001);
GMSCoordinateBounds *viewport = [[GMSCoordinateBounds alloc] initWithCoordinate:northEast
coordinate:southWest];
GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:viewport];
_placePicker = [[GMSPlacePicker alloc] initWithConfig:config];
[_placePicker pickPlaceWithCallback:^(GMSPlace *place, NSError *error) {
if (error != nil) {
NSLog(#"Pick Place error %#", [error localizedDescription]);
return;
}
if (place != nil) {
_name2 = place.name;
NSLog(place.name);
self.nameLabel.text = place.name;
_address2 = place.formattedAddress;
self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:#", "]
componentsJoinedByString:#"\n"];;
NSLog(place.formattedAddress);
_cat = place.types[0];
self.catLabel.text = place.types[0];
NSLog(_cat);
} else {
_name2 = #"No place selected";
_address2 = #"";
}
}];
}
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
#end
Also, is there any way I can use the place picker for the apple watch? Thanks!
By adding Core Location to the app I was able to get the coordinates for current location to be used in the place picker. Here's my code:
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(_locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude);
GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:nil];
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to get display top 10 cricket Grounds in map.
In my Code I got only one location, which is simulators default longitude and latitude values.
How to display multiple locations?
.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
Check below link.
http://jprithvi.wordpress.com/tag/display-multiple-pins-in-ios-map/
I hope this is what you are looking for.
Few more links.
http://jonathanfield.me/mkmapview-adding-pins-map-showing-annotations/
http://mayurbirari.wordpress.com/2011/02/07/how-to-access-mkmapkit-in-iphone/
http://sugartin.info/2011/07/01/map-view-controller-with-multiple-pin-on-google-map/
You'll able to display the user location by the classic user annotation on the map.
If you want to change your location in simulator, just add gpx files to your projet.
Then you will be able to switch between locations by this way : in xcode > debug > simulate locations
To add other locations on your map, you just have to add annotations (MKAnnontations)
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}.
So I am new to iOS development, and I am just trying to get a label updated with my current GPS Coordinates. I am not having an issue compiling, but my coordinates are coming up as 0.00000, 0.00000.
Here is the code for my .h file:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController{
IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *location;
}
//#property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
//#property (weak, nonatomic) IBOutlet UILabel *location;
#end
Here is the code for my .m file:
#implementation ViewController
- (void) updateLabel
{
NSObject *latitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSObject *longitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.longitude];
location.text = [NSString stringWithFormat: #"%#,%#", latitude, longitude];
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[self updateLabel];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Fixed it:
I wasn't implementing any delegate methods, and I was not implementing [locationManager startUpdatingLocation]. Now I know better.
.h File:
#interface MapViewController : UIViewController <CLLocationManagerDelegate>
#property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
#property (strong, nonatomic) IBOutlet UILabel *location;
#end
.m File:
- (void) updateCurrentLabel
{
NSObject *latitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSObject *longitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.longitude];
self.location.text = [NSString stringWithFormat: #"Current Location: %#,%#", latitude, longitude];
}
- (void)viewDidLoad
{
[self getCurrentLocation];
[super viewDidLoad];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[self updateCurrentLabel];
}
-(void) getCurrentLocation
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
Thanks for pointing out how nooby I was. Figured it out. Thanks guys!
once try like this,in ViewDidLoad:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = (id)self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
[self updateLabel];
Use this Delegate Method otherwise you will get 0 values:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//No need to do any code...
// NSLog(#"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
In Updating Label Method :
- (void) updateLabel
{
//Getting Current Latitude and longitude..
CLLocation *location = [locationManager location];
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"latitude,longitudes are >> %f,%f",latitude,longitude);
locationlabel.text = [NSString stringWithFormat:#"%f,%f",longitude,latitude];
}
Instead of using locationManager.location.coordinate.latitude, keep an instance variable of type CLLocationCoordinate2D. You can call it something like currentLocation. Then when you get a value in the delegate method locationManager:didUpdateLocations:, set the value of currentLocation.
You'll have to call [locationManager startUpdatingLocation] and set its delegate too (as well as implementing that delegate method).
The way you're using the location manager at the moment is wrong and I think you'd be better off following a tutorial to get the basics down.
I find this is fascinating to use location as singleton, and save the values into default user . I am young programmer and am trying to code all in oop. I use this as follow ( this code still need to be refactored and alertUserWithTitle: is a class method of NYMessageToUser to alert user):
//##Header file:
#interface NYLocationManager : NSObject<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
float lonngitude;
float latitude;
float altitude;
}
#property(nonatomic,retain)CLLocationManager *locationManager;
#property(nonatomic,readwrite)float longitude;
#property(nonatomic,readwrite)float latitude;
#property(nonatomic,readwrite)float altitude;
+(NYLocationManager *) getInstance;
-(void)startUpdatingLocation;
-(void)stopUpdatingLocation;
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon;
#end
//### implementation file:
#implementation NYLocationManager
#synthesize locationManager;
#synthesize latitude;
#synthesize longitude;
#synthesize altitude;
+ (id)getInstance
{
static NYLocationManager *Instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Instance = [[self alloc] init];
});
[Instance startUpdatingLocation];
return Instance;
}
- (id)init
{
if (self = [super init])
{
latitude =0.0;
longitude =0.0;
altitude =0.0;
if([[NSUserDefaults standardUserDefaults] objectForKey:#"locationLongitude"] != nil)
{
NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
latitude =[[savedLocation objectForKey:#"locationLatitude"] floatValue];
longitude =[[savedLocation objectForKey:#"locationLongitude"] floatValue];
altitude =[[savedLocation objectForKey:#"locationAltitude"] floatValue];
}
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled])
{
[locationManager startUpdatingLocation];
} else
{
[NYMessageToUser alertUserWithTitle:#"Location Services is Disabled!!!" withMessage:#"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
}
}
return self;
}
- (void)dealloc
{
// Should never be called, but just here for clarity really.
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *loc =[locations lastObject];
self.longitude =loc.coordinate.longitude;
self.latitude =loc.coordinate.latitude;
self.altitude =loc.altitude;
NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.longitude] forKey:#"locationLongitude"];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.latitude] forKey:#"locationLatitude"];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.altitude ] forKey:#"locationAltitude"];
[savedLocation synchronize];
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
[locationManager stopUpdatingLocation];
[NYMessageToUser alertUserWithTitle:#"Location Error!!!" withMessage:#"This app is designed to use with valid location, Please enable location for this app and relucnh the app"];
}
-(void)startUpdatingLocation
{
if ([CLLocationManager locationServicesEnabled])
{
[locationManager startUpdatingLocation];
} else
{
[NYMessageToUser alertUserWithTitle:#"Location Services is Disabled!!!" withMessage:#"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
}
}
-(void)stopUpdatingLocation
{
[locationManager stopUpdatingLocation];
}
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon
{
CLLocation *locA = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
CLLocationDistance distance = [locA distanceFromLocation:locB];
return distance;
}
#end
//### How to use
NYLocationManager *loc =[NYLocationManager getInstance];
NSLog(#"longitude: %f, latitude: %f, altitude: %f",loc.longitude,loc.latitude,loc.altitude);