Location Manager won't display latitude and longitude - ios

I have an app which displays the longitude and the latitude of the users position. The application asks for the current location, and the latitude and the longitude displays in Xcode. But in the app, nothing happens.
Here's my code:
- (NSString *)deviceLocation {
NSString *theLocation =
[NSString stringWithFormat:#"latitude: %f longitude: %f",
locationManager.location.coordinate.latitude,
locationManager.location.coordinate.longitude];
return theLocation;
}
In viewDidLoad:
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
The problem is that the latitude and longitude -labels won't show the position.

My guess is that you're not assigning your view controller as a delegate to CLLocationManager.
You can do that via:
locationManager.delegate = self;
Right after you create your locationManager.
Then, you can update labels by having your view controller respond to the delegate method locationManager:didUpdateLocations:.

Related

Change bearing based on rotateGestures in Google Maps for iOS

I'm using Google Maps SDK for iOS (version 2.1.1) with Xcode 8. I added a UIView and set its class to GMSMapView and linked up with an IBOutlet called mapView.
double bearing;
int zoomLevel;
- (void)viewDidLoad {
[super viewDidLoad];
bearing = 30;
zoomLevel = 20;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
if([CLLocationManager headingAvailable]) {
_locationManager.headingFilter = 5;
[_locationManager startUpdatingHeading];
}
mapView.myLocationEnabled = YES;
mapView.settings.tiltGestures = NO;
mapView.settings.scrollGestures = NO;
// obtain my position
CLLocation *myLocation = mapView.myLocation;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:zoomLevel
bearing:bearing
viewingAngle:45];
mapView.camera = camera;
}
The View Controller uses 2 delegates : CLLocationManagerDelegate and GMSMapViewDelegate.
Updating map location is not a problem, but when I rotate the map, since the bearing value has not changed at all, once the location is updated, the bearing is reset and cancelled the rotation. How can I update the bearing after I rotate the map?
Here is the didUpdateLocations: delegate function:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *myLocation = [locations lastObject];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:zoomLevel
bearing:bearing
viewingAngle:45];
[mapView animateToCameraPosition:camera];
}
My idea is to rotate the map exactly like the mobile game PokemonGO.

Google Maps API: Getting coordinates of current location iOS

I am currently working with Google Maps API in my project. I am trying to set the default camera/zoom to the users location. I do this:
#implementation ViewController{
GMSMapView *mapView_;
}
#synthesize currentLatitude,currentLongitude;
- (void)viewDidLoad
{
[super viewDidLoad];
mapView_.settings.myLocationButton = YES;
mapView_.myLocationEnabled = YES;
}
- (void)loadView{
CLLocation *myLocation = mapView_.myLocation;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = #"Current Location";
marker.map = mapView_;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView_;
NSLog(#"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);
}
However, it does not work, since when I do
NSLog(#"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);
it returns 0, 0, and it does not give the current location coordinates. How can I properly get the user's coordinates?
.h
#import <CoreLocation/CoreLocation.h>
#property(nonatomic,retain) CLLocationManager *locationManager;
.m
- (NSString *)deviceLocation
{
NSString *theLocation = [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
answered here.
When an app first starts it may not yet know your location, as it usually takes a while for the GPS device to lock on to your location (if it has just been started), and especially if this is the first time the application has been run, and so the user hasn't yet answered the prompt to give the app access to their location. Also it seems like mapView.myLocation is always empty (either nil or has coordinates 0,0) when the map view has just been created.
So you will need to wait until the user's location is known, and then update the camera position.
One way might be using the code at how to get current location in google map sdk in iphone as suggested by Puneet, but note that the sample code there is missing the details of setting up the location manager (like setting the location manager's delegate), which might be why it didn't work for you.
Another option could be to use KVO on mapView.myLocation, as described here: about positioning myself,some problems
By the way in your sample code you are accessing mapView.myLocation before you create the mapView, and so the location would always be nil anyway.
I just Downloaded the new GoogleMap SDK Demo for iOS. Here is what I have seen from the source code that how the "Current Location" is achieved via KVO.
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
#import "SDKDemos/Samples/MyLocationViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#implementation MyLocationViewController {
GMSMapView *mapView_;
BOOL firstLocationUpdate_;
}
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
// Listen to the myLocation property of GMSMapView.
[mapView_ addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
self.view = mapView_;
// Ask for My Location data after the map has already been added to the UI.
dispatch_async(dispatch_get_main_queue(), ^{
mapView_.myLocationEnabled = YES;
});
}
- (void)dealloc {
[mapView_ removeObserver:self
forKeyPath:#"myLocation"
context:NULL];
}
#pragma mark - KVO updates
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (!firstLocationUpdate_) {
// If the first location update has not yet been recieved, then jump to that
// location.
firstLocationUpdate_ = YES;
CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
zoom:14];
}
}
#end
Hope it can help you.
Just in case anyone wants DrDev's excellent answer in Swift 3:
var locationManager: CLLocationManager?
func deviceLocation() -> String {
let theLocation: String = "latitude: \(locationManager.location.coordinate.latitude) longitude: \(locationManager.location.coordinate.longitude)"
return theLocation
}
func viewDidLoad() {
locationManager = CLLocationManager()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// 100 m
locationManager.startUpdatingLocation()
}

Map reverting to user's location, not allowing 'browse' iOS

The map screen of the app displays the user's current location. I want to allow the user to 'browse' the map (scroll around and explore other areas) and I have a button which returns the user to the point on the map with their current location BUT I'm what's happening is that the app isn't allowing the user to 'browse' the map and retain the view they are looking at, rather it jumps right back to the user's current location.
Here is some code:
-(void) setupLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
tempLat = newLocation.coordinate.latitude;
tempLon = newLocation.coordinate.longitude;
CLLocationCoordinate2D currentLocation = CLLocationCoordinate2DMake(tempLat, tempLon);
MKCoordinateRegion viewRegionLocation = MKCoordinateRegionMakeWithDistance(currentLocation, 100, 100);
[self.mapView setRegion:viewRegionLocation animated:YES];
locationNew = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
locationOld = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
}
I also have:
- (IBAction)stopUpdating:(id)sender {
[locationManager stopUpdatingLocation];
}
And:
- (IBAction)findMe:(id)sender {
[locationManager startUpdatingLocation];
}
Any ideas of why the map keeps jumping back to the user's current location??
Thank you very much!
Because, in your - (void)locationManager: didUpdateToLocation: fromLocation: method you set the region of your mapview to the updated location everytime.
Removing this part will solve your problem.
MKCoordinateRegion viewRegionLocation = MKCoordinateRegionMakeWithDistance(currentLocation, 100, 100);
[self.mapView setRegion:viewRegionLocation animated:YES];
EDIT 1:
add this line in your viewDidLoad method,
self.mapView.showsUserLocation = YES;
change the find me button press method like this,
-(IBAction) findMeButtonPressed:(id)sender;{
MKCoordinateRegion viewRegionLocation = MKCoordinateRegionMakeWithDistance([self.locationManager location].coordinate, 100, 100);
[self.mapView setRegion:viewRegionLocation animated:YES];
}

Invalid Region error only on one device

I'm trying to show a map in my application, it works on my simulator and on my ipod touch 4g.
But I always get an error on my iPhone and I don't know why this happens.
Maybe you can explain me why it fails.
The error is:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid Region <center:nan, nan span:nan, nan>'
I already searched for solutions on google and stackoverflow but it seems that nobody has this problem.
Thats my code:
//setup mapview
mapView.delegate = self;
mapView.showsUserLocation = YES;
//set up core location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//Set up zoom location
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = locationManager.location.coordinate.latitude;
zoomLocation.longitude= locationManager.location.coordinate.longitude;
debug(#"Location: %f und %f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude);
//zoom to location
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
As I said, it works on iPod and simulator, but not on iPhone.
Hope you can help me
SOLUTION:
I used the locationManager too early, so the app crashed. Now I used it this way:
- (void)viewDidLoad {
[super viewDidLoad];
//setup mapview
mapView.delegate = self;
mapView.showsUserLocation = YES;
//set up core location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
//Set up zoom location
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = newLocation.coordinate.latitude;
zoomLocation.longitude= newLocation.coordinate.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
debug(#"Location: %f und %f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
}
Don't know if this way is 100% correct, but it works.

Drop pin at current user location iphone mkmapview

Ok, here's my attempt at using CLLoactionManager
- (void)viewDidLoad {
[super viewDidLoad];
mapView=[[MKMapView alloc] initWithFrame:self.view.frame];
//mapView.showsUserLocation=TRUE;
mapView.delegate=self;
[self.view insertSubview:mapView atIndex:0];
CLLocationManager *locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
mStoreLocationButton.hidden=FALSE;
location=newLocation.coordinate;
//One location is obtained.. just zoom to that location
MKCoordinateRegion region;
region.center=location;
MKCoordinateSpan span;
span.latitudeDelta=0.01;
span.longitudeDelta=0.01;
region.span=span;
[mapView setRegion:region animated:TRUE];
}
My problem is that [locationManager startUpdatingLocation]; doesn't seem to fire the next method. What am I missing? I've tried setting breakpoints in the second method, but they never catch. Obviously it's not being used.
You should look into using a CLLocationManager to get the current location to feed your MKMapView with the correct coordinates.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
MKMapView *map = [[MKMapView alloc] init];
[locationManager startUpdatingLocation];
CLLocationCoordinate2D _coordinate = locationManager.location.coordinate;
MKCoordinateRegion extentsRegion = MKCoordinateRegionMakeWithDistance(_coordinate, 800, 800);
[map setRegion:extentsRegion animated:YES];
This looks like a good place to start. In order to drop a pin, you need to know the coordinates. Using - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation will help you get the user's location so that you can create an MKAnnotation and MKPinAnnotationViews. Its pretty straight forward once you get started.

Resources