Google Maps iOS SDK, Getting Current Location of user

前端 未结 7 2393
渐次进展
渐次进展 2020-12-01 04:49

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 follo

相关标签:
7条回答
  • 2020-12-01 05:13

    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); 
       }
    }
    
    0 讨论(0)
  • 2020-12-01 05:18

    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.

    0 讨论(0)
  • 2020-12-01 05:20

    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
    
    0 讨论(0)
  • 2020-12-01 05:23

    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

    0 讨论(0)
  • 2020-12-01 05:26

    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!

    0 讨论(0)
  • 2020-12-01 05:36

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

    0 讨论(0)
提交回复
热议问题