以下是我用来加载地图视图的代码。
- (void)getLatLongCoordinates:(NSString*) addressStr firstNameTitle:(NSString*) firstNamesTitle lastNameTitle:(NSString*) lastNamesTitle {
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
[geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {
self.placemarksArray = placemarks;
CLPlacemark *placeInfo = [placemarks objectAtIndex:0];
mapCenter.latitude = placeInfo.location.coordinate.latitude;
mapCenter.longitude = placeInfo.location.coordinate.latitude;
[annotationPoint setCoordinate:mapCenter];
[annotationPointsArray addObject:annotationPoint];
addAnnotation = [[[MyAddressAnnotation alloc] initWithCoordinate:mapCenter title:firstNamesTitle SubTitle:lastNamesTitle ]autorelease];
addAnnotation.firstNameTitle = firstNamesTitle;
addAnnotation.lastNameTitle = lastNamesTitle;
[mapView addAnnotation:addAnnotation];
}];
}
我需要调用该方法[self zoomToFitMapAnnotations:mapView withArray:annotationPointsArray];
以最大缩放级别适合地图视图中的所有联系人。直到之前的实现我已经成功地使用了下面的代码。但是由于我现在使用块,所以我对何时调用此方法有点困惑。在调用此方法并将数组传递给它之前,我需要获取所有位置坐标。
-(void)zoomToFitMapAnnotations:(MKMapView*)mapViews withArray:(NSArray*)anAnnotationArray
{
if([mapViews.annotations count] == 0) return;
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for(MKPointAnnotation* annotation in anAnnotationArray)
{
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
region = [mapViews regionThatFits:region];
[mapView setRegion:region animated:NO];
}
上面这段代码中调用上述方法的正确位置在哪里,或者我是否需要找到其他方法来执行此操作。
编辑:我避免使用并直接从方法中mapCenter
访问坐标,我做对了,问题就解决了。但是我仍然很困惑,为什么第一种方法不起作用。placeInfo
getLatLongCoordinates