Graphics Programs Reference
In-Depth Information
MKCoordinateRegionMakeWithDistance
, allows you to specify a region with a
CLLocationCoordinate2D
and the north-south and east-west limits of the zoom in
meters. For the limits, we'll use 250 by 250 meters. For the coordinate, we need the user's
location. Where can we get that?
How about the
MKUserLocation
object that the
MKMapView
sends its delegate in the
mapView:didUpdateUserLocation:
message? Search the documentation for
MKUserLocation
, and you'll find it has a property called
location
that holds the
current location of the device. Keep drilling down, and you'll find that
location
points
to a
CLLocation
object, which has a
coordinate
property of type
CLLoca-
tionCoordinate2D
. Success! We can use information in the
MKUserLocation
to
prepare an
MKCoordinateRegion
, which we then can use to set the
region
property
of the map view.
From what we know now, getting the information from the
MKUserLocation
takes two
steps: we would send
MKUserLocation
the message
location
and then send the re-
turned
CLLocation
object the message
coordinate
. The data returned from
co-
ordinate
then would become the
MKCoordinateRegion
's
center
.
But nosing around the API Reference has its rewards. Before we add this code to
WhereamiViewController.m
, take another look at the
MKUserLocation
refer-
ence. At the top, it tells us that
MKUserLocation
conforms to the protocol
MKAn-
notation
. Click on the link for that protocol, and you'll see that classes conforming to
it are required to have a property named
coordinate
of type
CLLoca-
tionCoordinate2D
. So we can simplify the process and send the message
co-
ordinate
directly to the
MKUserLocation
.
In
WhereamiViewController.m
, add the new code to
mapView:didUpdateUserLocation:
.
- (void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
Notice that the
MKMapView
is sent the message
setRegion:animated:
instead of
simply
setRegion:
. What's the difference? Check the documentation.