I need to fit a certain bounds within a map. I get the bounds from calling the google geocoder and reading the viewport property which looks like:
{
northeast = {
lat = "30.4212235";
lng = "-97.486942";
};
southwest = {
lat = "30.1128403";
lng = "-97.99917959999999";
};
}
I then convert these into CLLocationCoordinate2D
NSDictionary *viewport = [[[results objectAtIndex:0] objectForKey:@"geometry"]
objectForKey:@"viewport"];
NSDictionary *NEDictionary = [viewport objectForKey:@"northeast"];
NSDictionary *SWDictionary = [viewport objectForKey:@"southwest"];
CLLocationCoordinate2D SWCoordinate =
CLLocationCoordinate2DMake(
[[SWDictionary objectForKey:@"lat"] floatValue],
[[SWDictionary objectForKey:@"lng"] floatValue]
);
CLLocationCoordinate2D NECoordinate =
CLLocationCoordinate2DMake(
[[NEDictionary objectForKey:@"lat"] floatValue],
[[NEDictionary objectForKey:@"lng"] floatValue]
);
I know I need to generate a MKMapRect (or MKMapRegion, whichever is easier) from these coordinates and then [mapView setVisibleRect:newRect animated:YES] (or [mapView setRegion:newRegion animated:YES] but I’m not quite sure how to get there. I need a method to convert the bounds into the proper data structure, something like:
- (MKMapRect) mapRectThatFitsBoundsSW:(CLLocationCoordinate2D)sw
NE:(CLLocationCoordinate2D)ne {
// CGFloat x = ??
// CGFloat y = ??
// CGFloat width = ??
// CGFloat height = ??
MKMapRect mapRectFromBounds = MKMapRectMake(x,y,width,height);
return mapRectFromBounds;
}
Any thoughts?
If your bounds can span the 180th meridian, you have to account for that in the conversion:
But beware those
MKMapRects that span the anitmeridian, because they come from the land where the dragons live. If you want to learn about some of the dangers that lie there, have a look atMKMapRect and displaying map overlays that span 180th meridian. You have been warned!