Get CLLocation coordinate from a method - ios

I follow a tutorial from http://www.vellios.com/2010/08/16/core-location-gps-tutorial/
to make an app to show user's current location.
It has a method called locationUpdate
- (void)locationUpdate:(CLLocation *)location {
//locLabel.text = [location description];
speedLabel.text = [NSString stringWithFormat:#"SPEED: %f", [location speed]];
latitudeLabel.text = [NSString stringWithFormat:#"LATITUDE: %f", location.coordinate.latitude];
longitudeLabel.text = [NSString stringWithFormat:#"LONGITUDE: %f", location.coordinate.longitude];
altitudeLabel.text = [NSString stringWithFormat:#"ALTITUDE: %f", [location altitude]];
}
How do i call location.coordinate.latitude outside this method?

Make a variable of CLLocation in your .h File, and then set that variable when the location updates (in the below method).
- (void)locationUpdate:(CLLocation *)location

Related

How to Get Center Location Latitude And Longitude of Google map in iOS?

i am newbie in iOS Development and new in map kit i want to know about Latitude and Longitude of MapView Center Every time Like as When User Scrollfrom one location to Another then i want to Show Center Latitude and Longitude of my GMSMapView how it Possible like as Here i Attach Image for it.
Here my Current Location is Mumbai Then It Shows My mapView like as
and i want to know Center Location Latitude and Longitude like as when user Scroll Mapview then i want to Know Latitude and Longitude of My Image Indicator Point. Here image Show as i want to Know Latitude and Longitude of this Point Here My Image indicated is in Center Position of my MapView.
To get the position whenever the map is moved, you'd want to handle mapView:didChangeCameraPosition:.
Then inside that method, you can access mapView.camera.target to get the current centre of the map.
- (void) mapView: (GMSMapView *)mapView
didChangeCameraPosition: (GMSCameraPosition *)position
{
double latitude = mapView.camera.target.latitude;
double longitude = mapView.camera.target.longitude;
// now do something with latitude and longitude
}
Note that to handle the delegate method, you'll need to implement the GMSMapViewDelegate protocol. When setting up the map, you'd need to set the map's delegate to the class which handles the protocol (usually self), eg:
mapView.delegate = self;
Use below code for getting center of mapview latitude and longitude .
When ever you scroll mapview in any direction automatically regionWillChangeAnimated: method will call.It's one of the optinal delegate method.
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(mkmapView.centerCoordinate.latitude, mkmapView.centerCoordinate.longitude);
CGFloat txtLatitude = coord.latitude;
CGFloat txtLongitude = coord.longitude;
NSLog(#"Latitude is===>>>%f %f",txtLongitude);
NSLog(#"Longitude is===>>>%f %f",txtLongitude);
}
If you tap the map view,you need that Latitude and Longitude use below code.
Here _mkMapView is outlet of Mapview.
- (void)viewDidLoad
{
UITapGestureRecognizer *tapGesture= [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(backgroundTapped:)];
[self.view addGestureRecognizer:tapGesture];
}
- (void)backgroundTapped:(UITapGestureRecognizer *)gesture
{
CGPoint touchPoint = [gesture locationInView:_mkMapView];
CLLocationCoordinate2D location =[_mkMapView convertPoint:touchPoint toCoordinateFromView:_mkMapView];
}
may be it will helpful for you.
- (void)mapView:(GMSMapView *)pMapView didChangeCameraPosition:(GMSCameraPosition *)position {
mapViewRef.delegate = self;
double latitude = mapViewRef.camera.target.latitude;
double longitude = mapViewRef.camera.target.longitude;
CLLocationCoordinate2D addressCoordinates = CLLocationCoordinate2DMake(latitude,longitude);
GMSGeocoder* coder = [[GMSGeocoder alloc] init];
[coder reverseGeocodeCoordinate:addressCoordinates completionHandler:^(GMSReverseGeocodeResponse *results, NSError *error) {
if (error) {
// NSLog(#"Error %#", error.description);
} else {
GMSAddress* address = [results firstResult];
NSArray *arr = [address valueForKey:#"lines"];
NSString *str1 = [NSString stringWithFormat:#"%lu",(unsigned long)[arr count]];
if ([str1 isEqualToString:#"0"]) {
self.txtPlaceSearch.text = #"";
}
else if ([str1 isEqualToString:#"1"]) {
NSString *str2 = [arr objectAtIndex:0];
self.txtPlaceSearch.text = str2;
}
else if ([str1 isEqualToString:#"2"]) {
NSString *str2 = [arr objectAtIndex:0];
NSString *str3 = [arr objectAtIndex:1];
self.txtPlaceSearch.text = [NSString stringWithFormat:#"%#,%#",str2,str3];
}
}
}];
}

GoogleMap not showing user's current location properly when drawing path overlay

I am using GMSPolyline on google map to show shortest path between two points. This map does not show user's current location properly.
Here is my code. Let me know about the correction that I can make in my code. Thanks in advance.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
/////// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 0.5)
{
/////// Update your marker on your map using location.coordinate.latitude
//and location.coordinate.longitude);
NSLog(#"event time=%#",eventDate);
#pragma mark start Point of Polyline Drow
///////////////Logitude 23.03 apvathe darek point tyathe start thay etle polyline Drow thay/////
if (location.coordinate.longitude==23.03)
{
[locationManager stopUpdatingLocation];
}
[mypath addObject:[NSString stringWithFormat:#"%f,%f",location.coordinate.latitude,location.coordinate.longitude]];
GMSMutablePath *path1 = [GMSMutablePath path];
for (int i=0; i<mypath.count; i++)
{
//NSString *str1=mypath[i];
NSArray* foo = [mypath[i] componentsSeparatedByString: #","];
NSString* lat = [foo objectAtIndex: 0];
NSString* longi = [foo objectAtIndex: 1];
[path1 addCoordinate:CLLocationCoordinate2DMake([lat floatValue], [longi floatValue])];
}
GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path1];
rectangle.map = mapView_;
marker.position = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
marker.title = #"Gurukul Road,Ahmedabad";
marker.snippet = #"Gujarat";
marker.map = mapView_;
}
}
you have to be more accurate in case of latitude and longitude you are using there %f and that is not accurate as per values of latitude and longitude use this code...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
strForCurrentLongitude= [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
strForCurrentLatitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
Take Double value instead of float in this line.
[path1 addCoordinate:CLLocationCoordinate2DMake([lat floatValue], [longi floatValue])];

Xcode: variables populate with breakpoints but not in realtime

I have a function that utilizes LocationManager for iOS development. The function fulfills the very common purpose of pulling latitude and longitude from the LocationManager object and populating some method variables to build a set of directions.
Currently the method works fine on the iOS simulator when there are some specifically placed breakpoints. I will step into each step until I see that the lat and long have been populated and then continue program execution. The view is correctly altered to bring up a set of directions.
If the breakpoints are removed however, the variables are never populated and the view defaults to 0.000 for lat and longitudes.
I also see an error in one of the threads (I'm completely unfamiliar with thread based programming. This is not my app I am debugging): Thread 1: EXC_BAD_ACCESS (CODE =1, address= {some address}
Below is the function code (asdf is just the instance name for LocationManager):
(void)webViewDidFinishLoad:(UIWebView *)webView
{
asdf = [[CLLocationManager alloc] init];
asdf.delegate = self;
asdf.distanceFilter = kCLDistanceFilterNone;
asdf.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[asdf startUpdatingLocation];
CLLocation *location = [asdf location];
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
double userLatitude = latitude;
double userLongitude = longitude;
[locationManager stopUpdatingLocation];
NSString *userLat = [NSString stringWithFormat:#"%f", userLatitude];
NSString *userLng = [NSString stringWithFormat:#"%f", userLongitude];
NSString *destinationLatitude = site.siteGPSN;
NSString *destinationLongitude = site.siteGPSW;
NSString *javascriptString = [NSString stringWithFormat:#"buildMap('%#','%#','%#','%#')",destinationLatitude, destinationLongitude, userLat, userLng];
[webView stringByEvaluatingJavaScriptFromString:javascriptString];
}
You're not using CLLocationManager correctly. You need to implement the CLLocationManagerDelegate. Otherwise there is no guarantee there will be a location object cached by the manager when you try to use it.
The implementation would look something like this:
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// handle error
}
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
// use location here
}
- (void) locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status == kCLAuthorizationStatusAuthorized)
{
[manager startUpdatingLocation];
}
}
Remember to call stopUpdatingLocation at the appropriate time as well (whenever you are done).
I would recommend looking at Apple's "LocateMe" sample project which provides some great starting code on how to use this protocol correctly.
https://developer.apple.com/library/ios/samplecode/LocateMe/Listings/Classes_GetLocationViewController_m.html#//apple_ref/doc/uid/DTS40007801-Classes_GetLocationViewController_m-DontLinkElementID_8
Location manager never gets an update as soon as you start it using startUpdatingLocation this is when the delegate methods come into action. Delegate methods are invoked only when a location update is available or the process failed for some reason.
I found that you have set:
asdf.delegate = self;
That means you are registering the current class as a handler for location updates. So you should declare the CLLocationManagerDelegate protocol in the header (.h file) of your class, like following:
#interface <# Your Class Name #> : NSObject<CLLocationManagerDelegate> // your class might have inherited from anything other than NSObject
////......
#end
Now in your implementation file (.m) implement the following methods:
-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations {
if (!locations || [locations count] == 0) {
return;
}
CLLocation* location = locations[[locations count] - 1];
if (location.horizontalAccuracy < 0) {
return;
}
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
double userLatitude = latitude;
double userLongitude = longitude;
//[locationManager stopUpdatingLocation]; -- dont stop it here
NSString *userLat = [NSString stringWithFormat:#"%f", userLatitude];
NSString *userLng = [NSString stringWithFormat:#"%f", userLongitude];
NSString *destinationLatitude = site.siteGPSN;
NSString *destinationLongitude = site.siteGPSW;
NSString *javascriptString = [NSString stringWithFormat:#"buildMap('%#','%#','%#','%#')",destinationLatitude, destinationLongitude, userLat, userLng];
[webView stringByEvaluatingJavaScriptFromString:javascriptString];
}
-(void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation { //for backward compatibility
if (newLocation.horizontalAccuracy < 0) {
return;
}
float longitude=newLocation.coordinate.longitude;
float latitude=newLocation.coordinate.latitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
double userLatitude = latitude;
double userLongitude = longitude;
//[locationManager stopUpdatingLocation]; -- dont stop it here
NSString *userLat = [NSString stringWithFormat:#"%f", userLatitude];
NSString *userLng = [NSString stringWithFormat:#"%f", userLongitude];
NSString *destinationLatitude = site.siteGPSN;
NSString *destinationLongitude = site.siteGPSW;
NSString *javascriptString = [NSString stringWithFormat:#"buildMap('%#','%#','%#','%#')",destinationLatitude, destinationLongitude, userLat, userLng];
[webView stringByEvaluatingJavaScriptFromString:javascriptString];
}
-(void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error {
NSLog(#"core location error: %#",[error localizedDescription]);
if ([error code] != kCLErrorLocationUnknown) { //when location update is not available for that time don't continue receiving updates
NSLog(#"location service will terminate now");
[manager stopUpdatingLocation];
}
}
After all these set up, your location manager would invoke the appropriate delegate method when an update is available (or failed) and you can stop your location service when you don't actually need it anymore, may be in your viewWillDisappear or dealloc methods.

longitude/latitude values are not correct

i try to catch the longitude and latitude values and to display them in the console (NSLog) for the moment, i have puted the correspondant code in the viewWillAppear method, any way, it's not a big deal, my problem is when i show the view the first time, my console show me that:
latitude: 0.000000
longitude:0.000000
and the second time it shows me that :
latitude : 134217731.444448
longitude : 0.700000
the third time :
latitude : 134217731.444448
longitude : 0.700000
the n time :
latitude : 134217731.444448
longitude : 0.700000
this my code in the viewWillAppear (i'm sure it's logic is pretty right and i'm waiting for your clarification):
-(void)viewWillAppear:(BOOL)animated
{
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude : %#", latitude);
NSLog(#"Longitude : %#",longitude);
}
note that i work on the iPhone simulator, thx for help :)))
You shouldn't check coordinate here.
Implement locationManager:didUpdateToLocation:fromLocation: method in the same class and check the location inside this method:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
CLLocationCoordinate2D coordinate = [newLocation coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude : %#", latitude);
NSLog(#"Longitude : %#",longitude);
}
Your current class should implement CLLocationManagerDelegate protocol, i.e. it should be a delegate of location manager.

longitude and latitude values are both 0.000000 , why?

i use core location to get the longitude and latitude value of my current position and i have displayed it into a label, so for my case it's always 0.000000 for both longitude and latitude, is it because i work on the simulator ??
//longitude and latitude
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
Just initialization the location manager doesn't fetch you values.
you have to write this
[self.locationManager startUpdatingLocation];
then you have to override a callback method
- (void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation {
[self.locationManager stopUpdatingLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", newLocation.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", newLocation.longitude];
[self.locationManager release];
}
Hope that helps!
Shuanak
No. CoreLocation on the iPhone simulator is fixed at 37.3317 North, 122.0307 West (Apple HQ).
Try moving your locationManager code away from your code with the label. Put the location manager code in the viewDidLoad or something and then put this code
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
in a function that you call from a button. CoreLocation needs time to get itself going. This is true on the device for sure, but perhaps it is also true on the simulator.

Resources