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
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.
Is there any way to get the only device gps location using the corelocation in ios.
Currently i am using the following code.
- (id)init{
if (!(self = [super init]))
return nil;
//Setup the manager
manager = [[CLLocationManager alloc] init];
if (!manager) {
return nil;
}
manager.distanceFilter = kCLDistanceFilterNone;
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
manager.desiredAccuracy = kCLLocationAccuracyBest;
manager.delegate = self;
if ([manager respondsToSelector:#selector(pausesLocationUpdatesAutomatically)]) {
manager.pausesLocationUpdatesAutomatically = NO;
}
if ([manager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[manager requestAlwaysAuthorization];
}
[manager startUpdatingLocation];
return self;
}
You should add this code to your file. It is executed when a new location is received:
// Delegate method from the CLLocationManagerDelegate protocol.
- (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) < 15.0) {
// If the event is recent, do something with it.
NSLog(#"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
}
}
src: Getting the Users Location - Apple
I am working on iOS app using Google Map SDK. I try to set on the CLLocationManager to get location of my device for 10 seconds and right bottom button to get my location instantly. When it comes to the implementation, the app show no response to initiate the method startUpdatingLocation to get my location. Would you please tell me the way to use locationManager to finish the aim?
The following is my working :
-(bool)isNetworkAvailable
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef address;
address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
CFRelease(address);
bool canReach = success
&& !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
&& (flags & kSCNetworkReachabilityFlagsReachable);
return canReach;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self getTime];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(#"Please enable location services");
return;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
if([self isNetworkAvailable]){
NSLog(#"connected ");
}else {
NSLog(#"not connected ");
}
CarArray = [[NSMutableArray alloc] init];
GMSMarker *marker = [[GMSMarker alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
NSLog(#"assadsd arrived map");
if(latitide!=0.00&&longitude!=0.00) {
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
camera = [GMSCameraPosition cameraWithLatitude:latitide longitude:longitude zoom:12];
}else{
camera = [GMSCameraPosition cameraWithLatitude:22.2855200 longitude:114.1576900 zoom:12];
marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
}
if(desp.length > 0 ){
marker.title = desp;
}
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest ;
self.locationManager.distanceFilter = 5.0f;
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
marker.snippet = #"HK";
marker.map = mapView_;
mapView_.mapType = kGMSTypeSatellite;
mapView_.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
mapView_.myLocationEnabled = YES;
});
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
[mapView_ addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
self.view = mapView_;
[self.locationManager startUpdatingLocation];
NSLog(#"assadsd configured d map");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
NSLog(#"CLLocationManager error: %#", error.localizedFailureReason);
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"application_name", nil) message:NSLocalizedString(#"location_error", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"ok", nil) otherButtonTitles:nil];
[errorAlert show];
return;
}
-(void) handleDoubleTap {
NSLog(#"location double tap ");
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
// Optional: check error for desired accuracy
CLLocation* location = [locations lastObject];
NSLog(#"location x : %f" , location.coordinate.longitude);
NSLog(#"location y : %f" , location.coordinate.latitude);
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
[manager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
if (markera == nil) {
markera = [[GMSMarker alloc] init] ;
markera.position = CLLocationCoordinate2DMake( location.coordinate.latitude , location.coordinate.longitude );
markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow
markera.map = mapView_;
}else {
markera.position = location.coordinate;
}
GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17];
[mapView_ animateWithCameraUpdate:move];
}
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()
}
}
I am using google map api in my app and I want when run my code show me my location automatic in view.
I write my code and run but my code not working and I understand that my location method don't save my coordinate location in two variable.why???
please guide me about it.
#implementation ViewController
{
double latitudes;
double longitudes;
CLLocationManager *locationManager;
GMSMapView *mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[self GetMyLocation];
// Create a GMSCameraPosition that tells the map to display the
//my friend I don't know why my two variable (latitudes,longitudes)
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitudes longitude:longitudes zoom:14];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
[mapView_ setMapType:kGMSTypeNormal];
}
- (void) GetMyLocation{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudes = currentLocation.coordinate.longitude;
latitudes = currentLocation.coordinate.latitude;
}
}
#end
#implementation ViewController
{
double latitudes;
double longitudes;
CLLocationManager *locationManager;
GMSMapView *mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[self GetMyLocation];
// Create a GMSCameraPosition that tells the map to display the
//my friend I don't know why my two variable (latitudes,longitudes)
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:0 longitude:0 zoom:14];
mapView_ = [GMSMapView mapWithFrame:self.view.frame camera:camera];
mapView_.myLocationEnabled = YES;
[mapView_ setMapType:kGMSTypeNormal];
[self.view addSubView:mapView_];
}
- (void) GetMyLocation{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudes = currentLocation.coordinate.longitude;
latitudes = currentLocation.coordinate.latitude;
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.longitude longitude:currentLocation.coordinate.latitude zoom:14];
[mapView_ animateToCameraPosition:camera];
}
#end