Alexyuiop
Alexyuiop

Reputation: 823

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?

Upvotes: 9

Views: 35505

Answers (4)

agrippa
agrippa

Reputation: 909

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()
}

Upvotes: 1

DrDev
DrDev

Reputation: 442

.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.

Upvotes: 11

TypingPanda
TypingPanda

Reputation: 1667

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.

Upvotes: 2

Saxon Druce
Saxon Druce

Reputation: 17624

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.

Upvotes: 6

Related Questions