我在旧金山有一个应用程序集,它在地图上绘制点。绘制点后,我使用此代码缩放并平移地图以适应所有点:
//BASE_RADIUS = 0.0144927536
- (MKCoordinateRegion)regionFromLocations:(NSArray*)locations {
if([locations count] <= 0) {
MKCoordinateRegion region = self.mapView.region;
return region;
}
CLLocationCoordinate2D upper = [[locations objectAtIndex:0] coordinate];
CLLocationCoordinate2D lower = [[locations objectAtIndex:0] coordinate];
// FIND LIMITS
for(MapPinModel *eachLocation in locations) {
if([eachLocation coordinate].latitude > upper.latitude) upper.latitude = [eachLocation coordinate].latitude;
if([eachLocation coordinate].latitude < lower.latitude) lower.latitude = [eachLocation coordinate].latitude;
if([eachLocation coordinate].longitude > upper.longitude) upper.longitude = [eachLocation coordinate].longitude;
if([eachLocation coordinate].longitude < lower.longitude) lower.longitude = [eachLocation coordinate].longitude;
}
// FIND REGION
MKCoordinateSpan locationSpan;
locationSpan.latitudeDelta = upper.latitude - lower.latitude;
locationSpan.longitudeDelta = upper.longitude - lower.longitude;
if(locationSpan.latitudeDelta < BASE_RADIUS) { locationSpan.latitudeDelta = BASE_RADIUS; }
if(locationSpan.longitudeDelta < BASE_RADIUS) { locationSpan.longitudeDelta = BASE_RADIUS; } //the smallest it gets is a mile.
CLLocationCoordinate2D locationCenter;
locationCenter.latitude = (upper.latitude + lower.latitude) / 2;
locationCenter.longitude = (upper.longitude + lower.longitude) / 2;
MKCoordinateRegion region = MKCoordinateRegionMake(locationCenter, locationSpan);
return region;
}
然后使用以下方法将地图缩放到此区域:
MKCoordinateRegion region = [self regionFromLocations:_data];
[mapView setRegion:region animated:YES]; //shows all the pins
大约95%的时间都有效。另外5%,地图放大到南极洲。奇怪的是,我已经在调试器中捕获了一次放大,并且坐标位于旧金山。关于这里可能发生什么的任何想法?