简体   繁体   中英

Google Maps iOS SDK: How to start map on user's location

I'm trying to set the initial center location of a GMSMapView. There's about 2000 tutorials out there that show you how to set it with arbitrary coordinates like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                            longitude:151.20
                                                                 zoom:6];

    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera2];

But I don't want to start in Australia and than move to wherever the user actually is. I want to just start wherever the user is, just like the way the Google Maps app works.

Here's what I think I know:

  • If I set mapView_.myLocationEnabled = YES; I should be able to retrieve the device position with mapView_.myLocation
  • BUT the GPS data is probably not available yet during viewDidLoad , so that value will be 0,0 initially or nil or whatever (something not useful).
  • Device location can be managed with a CLLocationManager to track if the device moves, etc.

But how do I pass the data that's (eventually) stored in the CLLocationManager to the GMSMapView so that I start in the right place?

This seems like it should not be so difficult, but after 2 hours of searching, I can't find the answer.

Here's what I've come up with so far...

This SO question is similar to mine: Could not get current location using Google Map API (GMSMapView)

And this blog post modifies the answer in the above post, with some really helpful explanation.

It seems to work, but there's still a bit of a glitchy flicker when it loads, and I think it's because of the way I'm setting the camera position initially. If anyone knows a better way to do this, please tell me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM