At the start of the application, the application request for user's current location. AlertBox pop up regarding about giving the app permission to access location services. My question is how do I get the location right after the user allows location services?
My Code
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[self.locationManager startUpdatingLocation];
latitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.latitude];
longtitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.longitude];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude floatValue]
longitude:[longtitude floatValue]
zoom:16];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView.delegate = self;
mapView.myLocationEnabled = YES;
self.view = mapView;
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake([latitude intValue], [longtitude intValue]);
marker.title = #"Current Location";
marker.map = mapView;
}
Is there any way to get user's current location once it allows location services?
My codes only works when user allows the location services then restart the app.
I tried implementing the code below as well. But the NSLog is not appearing.
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *loc = locations.lastObject;
double speed = loc.speed;
NSLog(#"speed-----%f ", speed);
}
Any advice? Did I left out anything?
Just put:
self.locationManager.delegate = self;
After this line:
self.locationManager = [[CLLocationManager alloc] init];
Note:
Make sure you have added CLLocationManagerDelegate in your header file.
My answer comes a year too late and I'm using Swift 2 but for anyone else requiring an answer:
You need to update the mapview in the didUpdateLocations delegate. Please see the code below.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapUIView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
Related
This question already has answers here:
How to find your current location with CoreLocation
(3 answers)
Closed 6 years ago.
I am working in google map in my app. i get default location on map currently. but i need to get current location of device an show it on map. There are lots of solution are there on stackoverlfow, but somehow its not working in my case. These solution work if i add map on default view.Look at my little bit code.
.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import GoogleMaps;
#interface ViewController : UIViewController<CLLocationManagerDelegate, GMSMapViewDelegate>
#property (weak, nonatomic) IBOutlet UIView *maponScreem;
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
.m file
self.locationManager.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[self.locationManager startUpdatingLocation];
latitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.latitude];
longtitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.longitude];
NSLog(#"%#", latitude);
NSLog(#"%#", longtitude);
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude floatValue]
longitude:[longtitude floatValue]
zoom:12];
mapView_ = [GMSMapView mapWithFrame:self.maponScreem.bounds camera:camera];
mapView_.delegate = self;
mapView_.myLocationEnabled = YES;
[self.maponScreem addSubview: self->mapView_];
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake([latitude intValue], [longtitude intValue]);
marker.title = #"Current Location";
marker.map = mapView_;
i get 0.000000 for attitude and longitude.
EDIT:
i found solution and look at this how it works. Thanks to you all for answers and support me.
- (void)viewDidLoad {
[super viewDidLoad];
if (self.locationManager == nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
else
{
nil;
}
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
else
{
nil;
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:CLLocationCoordinate2DMake(0, 0) zoom: 16];
mapView_ = [GMSMapView mapWithFrame:self.maponScreem.bounds camera:camera];
mapView_.myLocationEnabled = YES;
[self.maponScreem addSubview: self->mapView_];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
NSString *lasti = [NSString stringWithFormat:#"%f", location.coordinate.latitude];
NSString *longi = [NSString stringWithFormat:#"%f", location.coordinate.longitude];
// NSLog(#"%#", lat);
// NSLog(#"%#", longi);
[mapView_ animateToLocation:location.coordinate];
}
You have not initialized your locationManager and also you need to ask user permission for location access and set its delegate.Use following code before starting location updates.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization]; //gives alert for location access
}
It will give you user location.
Hope it helps :)
EDIT
You should use below method to receive location updates
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations
The method you have used is deprecated.
#property (nonatomic, retain) IBOutlet GMSMapView *googleMapView;
#property (nonatomic, retain) CLLocationManager *locationManager;
- (void)showCurrentLocation {
_googleMapView.myLocationEnabled = YES;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
longitude:newLocation.coordinate.longitude
zoom:17.0];
[_googleMapView animateToCameraPosition:camera];
//...
}
I hope this will help you..
- (IBAction)btnSetDistance:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.distanceFilter =//as per your requirment;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
This is important
Enable Background Modes from--- Project, Capabilities Tab, and choose Location Updates...
you should check it on device instead of simulator.
i am getting current attitude and longitude of device and print it with nslog but now how will update these latttitude and longitude on map accordingly. here is my code please look at this.
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.settings.myLocationButton = YES;
self.view = mapView_;
mapView_.settings.compassButton = YES;
[self startStandardUpdates];
}
- (void)startStandardUpdates
{
// Create the location manager if this object does not
// already have one.
NSLog(#"startupdatelocation");
if (nil == _locationManager)
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
_locationManager.distanceFilter = 10; // meters
[self.locationManager startUpdatingLocation];
}
- (void)startSignificantChangeUpdates
{
// Create the location manager if this object does not
// already have one.
if (nil == _locationManager)
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSLog(#"location %#", location);
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// If the event is recent, do something with it.
NSLog(#"latitude %+.6f, longitude %+.6f\n",location.coordinate.latitude,
location.coordinate.longitude);
}
}
i am printing current latitude and longitude now how will i show this location on map also please help me in this situation.
Current device location should be requested from the iOS - https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html
than you could show the marker with device location on the map
I have an iOS app that uses a users current location to show directions/ distance between the users current location and a destination point. I am able to show the destination point on the map, however when I try to get the user's current location using CLlocationManager, it returns coordinates (0,0). Below is my code for retrieving the users location.
Is retrieving current location possible on the Apple Watch?
If so, what am I doing wrong here that the location is returning (0,0)?
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = 5;
CLLocation *location = locationManager.location;
CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
Also, I have #import < CoreLocation/CoreLocation.h> in my .h file and < CLLocationManagerDelegate>
Try the following code:
#property (nonatomic, strong) CLLocationManager *locationManager;
- (void)willActivate
{
self.locationManager = [[CLLocationManager alloc] init];
[self.locationManager setDelegate:self];
[self.locationManager requestLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
if ([locations count] == 0) {
// error
return;
}
// success
self.currentLocation = [locations firstObject];
CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(
self.currentLocation.coordinate.latitude,
self.currentLocation.coordinate.longitude);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(nonnull NSError *)error
{
// error
}
If you did not implemented this:
(with attributes inspector or programmatically)
self.mapView.showsUserLocation = YES
Or in addition to tell the mapView that the user's location is depending of LocationManager.location
I am building an app which requires me to find the distance between a location specified and my current location.
I am using CLLocationManager for the same but the coordinates retrieved are 0,0 despite me specifying a custom location in the simulator. Here's the code:
The .m file
#property (nonatomic, strong) CLLocationManager *locationManager2;
...
#synthesize locationManager2;
- (CLLocationManager *)locationManager2 {
if (locationManager2 != nil) {
return locationManager2;
}
locationManager2 = [[CLLocationManager alloc] init];
[locationManager2 setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager2 setDelegate:self];
return locationManager2;
}
...
...
...
CLLocation *locationHome = [locationManager2 location];
NSLog(#"%f",locationHome.coordinate.latitude);
The lattitude is logged as zero.Anything wrong with my code?
Put this code and let me know what you are getting at console.
This code built on iOS 6.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
MKCoordinateRegion region;
region.center=coordinate;
MKCoordinateSpan span;
span.latitudeDelta=10.015;
span.longitudeDelta=10.015;
region.span=span;
[mapView setRegion:region];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);
I want to receive in coordinates the users current location and I entered this code:
-(void)update{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
mapView.showsUserLocation = YES;
[locationManager startUpdatingLocation];
}
On iOS Simulator, this code is crashing and on my device it is not or sometimes its crashes the whole app.... can you help me on what is going on?
It looks like maybe you're not implementing the CLLocationManagerDelegate methods.
In particular -locationManager:didUpdateLocations: (from iOS 6) or -locationManager:didUpdateToLocation:fromLocation: in previous iOS versions.
Maybe (again your question is so vague) you only want to show the blue dot on a map view. In which case you don't need to deal with the Core Location Manager. Check out this post for more information.
1st of all You can't get your current Location in the Simulator . and try with this code for getting the co-ordinates of current Location.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
MKCoordinateRegion region;
region.center=coordinate;
MKCoordinateSpan span;
span.latitudeDelta=10.015;
span.longitudeDelta=10.015;
region.span=span;
[mapView setRegion:region];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);