14

For my iOS app (building in iOS7),i need to show user's current location when the app load.I am using Google Maps iOS SDK. I am following this Google Map But i can't figure it out. Please help if you go through the path.

Julian
  • 9,299
  • 5
  • 48
  • 65
Sofeda
  • 1,361
  • 1
  • 13
  • 23

7 Answers7

40

Forget my previous answer. It works well if you use the native MapKit.framework.

In fact GoogleMaps for iOS do all the work for you. You don't have to use CoreLocation directly.

The only thing you have to do is to add yourMapView.myLocationEnabled = YES; and the framework will do everything. (Except center the map on you position).

What I have done : I simply followed the steps of the following documentation. And I got a map centered on Sydney but if I zoomed out and moved to my place (if you use a real device, otherwise use simulator tools to center on Apple's location), I could see the blue point on my position.

Now if you want to update the map to follow your position, you can copy Google example MyLocationViewController.m that is included in the framework directory. They just add a observer on the myLocation property to update the camera properties:

@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

With the doc I gave you and the samples included in the framework you should be able to do what you want.

Maxime Capelle
  • 887
  • 7
  • 16
  • Yes i see it.And when the example starts it loads with Sydney and after pinching i can see my location.I want at first it loads with the blue point with my current loaction.I just can't catch the informations behind mapView_.settings.myLocationButton.If i can get my current location's JSON it will make me blasshing! – Sofeda Jan 08 '14 at 11:30
  • That is exactly what the code above do (`MyLocationViewController.m`). When I launch the app on my iPhone I get the map centered on my position. To make a JSON with your current location, you probably should put your code in the method triggered by the observer. There you can build a JSON with your coordinates and make what you want with this. – Maxime Capelle Jan 08 '14 at 11:42
  • WOW!! let me work with it.Do you try Google maps search?where i put a string and get related JSONs? – Sofeda Jan 08 '14 at 12:08
  • No I didn't try search requests. – Maxime Capelle Jan 08 '14 at 15:52
  • @MaximeCapelle Thanks for your detailed answer. When I run the code, the maps shows the blue point at top left corner, instead of center of the screen. Just wondering if you have any ideas. – Indrajeet Mar 11 '14 at 03:25
  • keep in mind: if VC is allocated but never loaded, it will crash on `dealloc` trying to remove observer (which is not present), because you start KVO in `viewDidLoad` – DanSkeel Dec 28 '15 at 13:00
  • DO NOT forget to set one of these keys in your Info.plist: `NSLocationWhenInUseUsageDescription` or `NSLocationAlwaysUsageDescription` – hash3r Feb 03 '16 at 18:51
10

It seems Google Maps iOS SDKcannot access to the device position. So you have to retrieve the position by using CLLocationManagerof iOS.

First, add the CoreLocation.framework to your project :

  • Go in Project Navigator
  • Select your project
  • Click on the tab Build Phases
  • Add the CoreLocation.framework in the Link Binary with Libraries

Then all you need to do is to follow the basic exemple of Apple documentation.

  • Create a CLLocationManager probably in your ViewDidLoad:

    if (nil == locationManager)
        locationManager = [[CLLocationManager alloc] init];
    
    locationManager.delegate = self;
    //Configure Accuracy depending on your needs, default is kCLLocationAccuracyBest
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    
    // Set a movement threshold for new events.
    locationManager.distanceFilter = 500; // meters
    
    [locationManager startUpdatingLocation];
    

With the CLLocationManagerDelegate every time the position is updated, you can update the user position on your Google Maps :

- (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) {
      // Update your marker on your map using location.coordinate.latitude
      //and location.coordinate.longitude); 
   }
}
Maxime Capelle
  • 887
  • 7
  • 16
  • Thanks a lot.One more thing need to know,can i use google GMSMapView here to present the position? or i have to use MKMapView? – Sofeda Jan 07 '14 at 09:50
  • Yes you need to use Google GMSMapView and GMSMarker. MKMapView is only if you use native iOS MapKit. – Maxime Capelle Jan 07 '14 at 09:56
  • Please Maxime help to use GMSMapView. – Sofeda Jan 07 '14 at 10:23
  • Regarding [Google documentation](https://developers.google.com/maps/documentation/ios/reference/interface_g_m_s_map_view), you need to activate location when you instantiate your `GMSMapView`with `yourMapView.myLocationEnabled = YES;` and in `CLLocationManager Delegate` method, try to update the property `yourMapView.myLocation(location)`. Here the argument `location` is the `CLLocation` retrieved from the delegate. I think you should get the usually blue spot on your map. – Maxime Capelle Jan 07 '14 at 12:06
  • yourMapView means an object of GMSMapView? As i am new with Location so if you can help me with any example it will be blessing for me. – Sofeda Jan 08 '14 at 03:32
  • i got my Current Location.How i can present it in GMSMapView? – Sofeda Jan 08 '14 at 04:28
3

Xcode + Swift + Google Maps iOS

Step by step recipe:

1.) Add key string to Info.plist (open as source code):

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs your location to function properly</string>

2.) Add CLLocationManagerDelegate to your view controller class:

class MapViewController: UIViewController, CLLocationManagerDelegate {
   ...
}

3.) Add CLLocationManager into your class:

var mLocationManager = CLLocationManager()
var mDidFindMyLocation = false

4.) Ask for permission and add observer:

override func viewDidLoad() {
        super.viewDidLoad()          

        mLocationManager.delegate = self
        mLocationManager.requestWhenInUseAuthorization()
        yourMapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)
        ...
}

5.) Wait for authorization and enable location in Google Maps:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        if (status == CLAuthorizationStatus.authorizedWhenInUse) {
            yourMapView.isMyLocationEnabled = true
        }

    }

6.) Add observable for change of location:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if (!mDidFindMyLocation) {

            let myLocation: CLLocation = change![NSKeyValueChangeKey.newKey] as! CLLocation

            // do whatever you want here with the location
            yourMapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 10.0)
            yourMapView.settings.myLocationButton = true

            mDidFindMyLocation = true

            print("found location!")

        }

    }

That's it!

lenooh
  • 10,364
  • 5
  • 58
  • 49
2

On any iOS device, get the user's location with Core Location. Specifically, you want the CLLocation class (and CLLocationManager).

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • Is this only way? As i am using Google Maps iOS SDK so can't i get it from here?What i will do when i need to search depend on user current location? – Sofeda Jan 07 '14 at 09:27
  • @SMi it's the right way. Skimming through the Google Maps SDK documentation, there doesn't seem to be a way to extract the current location. That doesn't surprise me, Google engineers tend to be quite clever and would not reinvent the wheel without good reason. Core Location is not hard to use (look at Maxime's answer). – JeremyP Jan 07 '14 at 09:33
  • thanks a lot.but when i see my currentLocation at google map it is quite specific.I just want the detaile position address.As you asure me it is the right way so i will on this way... – Sofeda Jan 07 '14 at 09:44
1

Is delegate method didTapMyLocationButton is not way?

https://developers.google.com/maps/documentation/ios/reference/protocol_g_m_s_map_view_delegate-p#ac0e0171b811e839d9021800ca9fd33f4

- (BOOL)didTapMyLocationButtonForMapView:(GMSMapView *)mapView {
    return YES;
}

And you can get location by

(lldb) po mapView.myLocation
<+37.33243033,-122.03088128> +/- 386.93m (speed -1.00 mps / course -1.00) @ 5/19/14, 6:22:28 PM Moscow Standard Time
Dmitry Nelepov
  • 7,246
  • 8
  • 53
  • 74
0

The current location won't show on the simulator... connect a real device and give it a try I spent 2 days running in the simulator and don't know that it doesn't simulate locations

-2

there are many methods... I used this method and it works in all cases. Google gives you everything with the reponse in json format and its on you how you deal with that data.

Some steps are there to load google map in your project.

  1. find the api key from this link https://developers.google.com/places/ios-api/ sign in with your google account and add your project and create a ios key. then use this in your project

  2. enable all the api needed for google map

a-googlemaps sdk for ios b-googlemap direction api c-" " javasripts api d- picker api e- places api for ios f distance matrix api

in appdelegate method...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [GMSServices provideAPIKey:@"xxxxxxxx4rilCeZeUhPORXWNJVpUoxxxxxxxx"];

    return YES;
}
  1. add all needed library and frameworks in your project if google map is not working it means you have to add required framework all the best play with google map
Jasper
  • 7,031
  • 3
  • 35
  • 43