Brandon Brandon - 1 year ago 76
iOS Question

Focus MKMapView on NSString Latitude and Longitude Coordinates with MKCoordinateRegion

I have a latitude and longitude coordinate that I would like to focus my map on. They are stored as NSStrings and converted to locations below:

NSString *placeLatitude = [elementCoords objectForKey:@"placeLatitude"];
NSString *placeLongitude = [elementCoords objectForKey:@"placeLongitude"];

CLLocationCoordinate2D location;
location.latitude = [placeLatitude doubleValue];
location.longitude = [placeLongitude doubleValue];

How would I modify the below to not focus on the user's current location, but on the latitude and longitude specified above?

MKCoordinateRegion mapRegion; = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.05;
mapRegion.span.longitudeDelta = 0.05;

Answer Source

I would use setCenterCoordinate:animated: in order to move the map focus point. If you're loading the view and want to have it set to the correct location immediately, set animated:NO, otherwise, if you want to pan the map to smoothly center on location then set animated:YES

[mapView setCenterCoordinate:location animated:YES];

Of course, this won't change the zoom level of the map view. If you want to update the zoom level you should use setRegion:animated:. For example, if you want to zoom in twice as close:

// Halve the width and height in the zoom level.
// If you want a constant zoom level, just set .longitude/latitudeDelta to the
// constant amount you would like.
// Note: a constant longitude/latitude != constant distance depending on distance
//       from poles or equator.
MKCoordinateSpan span =
    { .longitudeDelta = mapView.region.span.longitudeDelta / 2,
      .latitudeDelta  = mapView.region.span.latitudeDelta  / 2 };

// Create a new MKMapRegion with the new span, using the center we want.
MKCoordinateRegion region = { .center = location, .span = span };
[mapView setRegion:region animated:YES];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download