Hard to get the geofencing running on test phone - IOS - ios

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.

Related

How do I get the user location for the Google Places API Place Picker to work?

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];

Core Location delegate methods not getting called in iOS 8.3 Xcode 6.3.1

I am trying to get the user's current location using the Core Location Framework in Xcode 6.3.1, I did following things:
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
My ViewController.h file is as shown below,
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
#property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
#property (weak, nonatomic) IBOutlet UILabel *lblAddress;
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
My ViewController.m file is as shown below,
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[self.locationManager requestAlwaysAuthorization];
} else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[self.locationManager requestWhenInUseAuthorization];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[self.locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
lblLatitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lblLongitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end
I had also added the following keys in my info.plist file
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Checked everything given here, here, here, here, and a lot more list
So, is anyone having a solution for this issue, kindly help. Have lost my mind searching for this for the whole day.
Yeah! Got the solution, Here is my whole code & things added to make it working. Special thanks to #MBarton for his great help. Also Thanks to # Vinh Nguyen for investing his precious time in solving my issue.
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
Added in .plist file
NSLocationAlwaysUsageDescription
See Screenshot:
In my ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
// #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
__weak IBOutlet UINavigationItem *navigationItem;
}
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property(nonatomic, retain) CLLocationManager *locationManager;
#end
Then in ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setUpMap];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUpMap
{
mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
// if(IS_OS_8_OR_LATER) {
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
Ufff...! Got the solution after fighting with many codes since last 5 days...

Trouble with getting location on iphone 6.1 simulator

I am very new to objective C and Xcode. I was trying to find out the location of my iphone simulator and went through a tutorial on youtube. Following is the code.
#import "MainClassViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface MainClassViewController () <CLLocationManagerDelegate>
#end
#implementation MainClassViewController
{
CLLocationManager *manager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
manager = [[CLLocationManager alloc]init];
}
- (IBAction)LocationButton:(id)sender
{
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager startUpdatingLocation];
}
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(CLLocation *)newLocation fromLocation: (CLLocation *) oldLocation {
NSLog(#"Location: %#", newLocation);
CLLocation *currentLocation = newLocation;
if(currentLocation != nil){
_Lattitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
_Longitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
}
}
#end
#import <UIKit/UIKit.h>
#interface MainClassViewController : UIViewController
- (IBAction)LocationButton:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *Lattitude;
#property (weak, nonatomic) IBOutlet UILabel *Longitude;
#end
My questions are:
1. I am not sure why labels are not getting updated with location.
2. I want to learn more about debugging. Any suitable resources available. Please keep in mind I do not want learn all about debugging. Only what is required for the basics.

UIlabel doesn't update user current speed

been having this problem for a few days now and can't seem to find a solution for it. It's probably some very basic stuff but still can't come up with a solution. So I'm trying to have my uilabel update a user speed in a car or on bike. But When the UIlabel update, it doesn't update the correct value. Any help will be appreciated.
Heres my .h file
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MainViewController : UIViewController <LoginDelegate,WEPopoverParentView,PopoverControllerDelegate,MainMenuDelegate,MKMapViewDelegate,UIActionSheetDelegate,UIAccelerometerDelegate, CLLocationManagerDelegate, NSObject>
{
AppDelegate *appDelegate;
IBOutlet MKMapView *userMap;
CLLocationManager *locationManager;
}
#property (strong, nonatomic) IBOutlet UILabel *speedView;
#property(nonatomic) int speedCount;
#property (nonatomic,retain) CLLocationManager *locationManager;
#property (nonatomic, strong) WEPopoverController *popoverController;
+ (NSString *) speedToMPH: (float) value;
- (IBAction)btnMenuTapped:(id)sender;
#end
and my .h file
#implementation MainViewController
#synthesize speedCount;
#synthesize speedView;
#synthesize popoverController;
#synthesize locationManager;
- (void)locationError:(NSError *)error {
speedView.text = [error description];
}
-(void)viewWillAppear:(BOOL)animated
{
[userMap setRegion:MKCoordinateRegionMakeWithDistance(userMap.userLocation.coordinate, 5, 5) animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = [[UIApplication sharedApplication] delegate];
locationManager =[[CLLocationManager alloc] init];
// Do any additional setup after loading the view, typically from a nib.
[userMap setCenterCoordinate: userMap.userLocation.coordinate animated: YES];
[self performSelector:#selector(checkForLogin) withObject:nil afterDelay:1];
[self startLocationServices];
// create LM
self.locationManager = [CLLocationManager new];
// set its delegate
[self.locationManager setDelegate:self];
// set configuration
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
// start location services
[self.locationManager startUpdatingLocation];
// create an oldLocation variable if one doesn't exist
}
- (void)startLocationServices
{
// create the Location Manager
if (self.locationManager == nil) {
self.locationManager = [CLLocationManager new];
}
// stop services
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
self.speedView.text = #"Location Services stopped.";
}
// locationManager didUpdateToLocation FromLocation
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%#", newLocation);
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed]];
}
+ (NSString *) speedToMPH: (float) value
{
NSString *speedCount = #"0.0 ";
if (value>0) {
float mile = 1609.344f;
float mph = value / mile * 3600;
speedCount = [NSString stringWithFormat: #"%.f ", mph];
}
return speedCount;
}
CLLocation returns the speed in meters per second. So you will have to convert it to miles per hour by multiplying the value with 2.23694.
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed] * 2.23694];

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