首页 > 解决方案 > Show User Location with MKMapKit (Objective C)

问题描述

I am currently learning to use the MKMapKit framework for iOS but can't really find any good tutorials as most of those are in Swift (a language I have not yet learned) or just simply too old to be relevant. So I was wondering if you guys might be able to answer a few specific questions regarding displaying user location and permissions.

My code is bare bones currently, I have a MKMapView initialised, which works just fine:

@interface ViewController () <MKMapViewDelegate>

...

mapView.frame                               = CGRectMake(0, 0, windowSize.width, windowSize.height);
mapView.delegate                            = self;
mapView.showsUserLocation                   = YES;
[self.view addSubview:mapView];

And a method to zoom in on a specific location on the map:

- (void)setLocation:(CLLocationCoordinate2D)location {
    float perimeter                             = 250.0f;
    [mapView setRegion:MKCoordinateRegionMakeWithDistance(location, perimeter, perimeter) animated:YES];
}

This displays a predetermined location whose coordinates I got from Google maps. This is all good and well, but now I would like to add a button to my app to locate the user's current position and zoom in on it. But this is where I get lost. I cannot find any good tutorial that would plainly explain to me how to achieve this with Obj C. Some talk about CLCoreLocation and its delegates, some say it is doable just with MKMapKit, but nothing worked so far.

Also, I am having trouble asking for permission to use the phone's GPS. I have added the following line to the info.plist file:

Privacy - Location When In Use Usage Description

I also added a string as its value, but cannot seem to trigger the pop up window to allow me access to the GPS. In one try, the window showed up for a second but then immediately disappeared. So, I am at a loss there too.

Basically here is whathat I would like to achieve:

  1. Ask for permission to use the GPS when the app first starts or when the user taps on the current location button (in case he or she mistakenly said no to the permission).
  2. If there is permission, the app should zoom in on the user's location by default or, if the permission is not granted, to a predetermined location (this last part actually works now).
  3. The app should not follow the user's movement but stay stationary allowing the user to freely pan and zoom. However, if the user taps on the "Current Location" button, it should zoom in on his or her location like at startup.

Could anyone please help me with this and perhaps write a few lines as to why things work that way? There are no current tutorials out there for Objective C, so I think this could really be helpful for others as well.

A few additional info: I use Xcode 9.3 and do everything programmatically (I do not use interface builder).

Thanks a bunch!

标签: iosobjective-clocationmapkit

解决方案


1. Requesting Location Updates

To request location updates, you need a CLLocationManager. You need to set up a receiver class to be a CLLocationManagerDelegate.

    //Create location manager
    locationManager = [[CLLocationManager alloc] init];
    //Subscribe to location updates
    [locationManager setDelegate:self];
    //Request always authorization
    [locationManager requestAlwaysAuthorization];
    //Start location updates
    [locationManager startUpdatingLocation];
    //Start heading updates
    [locationManager startUpdatingHeading];
    //Receive all updates
    locationManager.distanceFilter = kCLDistanceFilterNone;
    //Get best possible accuracy
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

Your receiver class needs to implement the

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status 

method on that class. This is where you check to see if your app has been given permission. If status == kCLAuthorizationStatusDenied, the user has rejected your request. If status == kCLAuthorizationStatusAuthorizedAlways or kCLAuthorizationStatusAuthorizedWhenInUse, you can retrieve the user's location. Then you can just retrieve the location from the location manager.

locationManager.location

If the user rejects your request for location access, you cannot ask again from within the app. You can, however, ask them to change the setting and use an openURL: call to send them to the privacy settings for your app.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

2. Moving to the user location

Moving the map to the user location is very simple. It can be done with one line of code.

[map setCenterCoordinate:map.userLocation.coordinate animated:YES];

3.

This is already the default behavior of MapKit.


推荐阅读