Why is the MKMapView's userLocation property r

2020-04-11 18:44发布

问题:

I have a Map View defined in IB and it is set to show the user location.

In my app, in -viewDidAppear, I query self.mapView.userLocation.location.coordinate and it comes back with insane values such as:

latitude: 4.8194501961644877e-49
longitude: 2.2993313035571993e-59

However, the next time -viewDidAppear is called (after I've simply moved to another tabbed view and then back to this one) the userLocation property holds exactly the correct values for my current location.

It seems that at the time of my initial call, the userLocation property has not been initialised but despite having read Apple's documentation I can't see any caveats where it says that this property is only valid after doing xxx.

Is there something that has to happen before userLocation is valid to use or should I just use CLLocationManager and ask it instead?

Thanks in advance for any help.

Sadly, Thomas' suggestion didn't help. What I have since discovered is:

If showsUserLocation is NO, then userLocation is never set correctly and -MapView:didUpdateUserLocation: is never called, consequently I never ever get a sensible location value.

So, to get the user's location I have to set showsUserLocation to YES, however that then means that after all my annotations have been added to the view (without including the user's location) I then calculate the required span to encompass them all and display them all at the right zoom level. After I do that though, the view jumps sideways as the Map View then automatically displays the user's location as the blue blob! As it was never included in the annotations to work out the zoom level I can't incorporate it into my calculations. Aaargh!

Note that when showsUserLocation is YES, then -MapView:didUpdateUserLocation: is called, but only after I've calculated all the coordinates of my annotations, not before!

回答1:

I'm assuming it hasn't finished finding the user location - it has to work this out and it may take a while.

Instead of using it in viewDidLoad use THIS delegate method:

- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation;

You will need to set your mapview delegate to self. :)



回答2:

Same is often true of Core Location. You'll get the last location lingering it its buffer, sometimes, or a super-broad throw-the-dart-at-the-map kind of location...

Best bet is to check the .horizontalAccuracy property of the location object and toss any that are too vague. It's good practice to just chuck the first one too.



回答3:

for didUpdateUserLocation to be called you have to have... mapView.showsUserLocation = TRUE;