我对Objective-C只有几个月的经验。
我有一个代码来搜索客户地址列表,然后显示这些地址的注释。由于客户覆盖了许多地区,我想让地图视图的中心和跨度适应结果。
因此,我计划记录所有搜索到的地方标记并计算平均纬度和经度。以下是我的代码
self.mapView.mapType = MKMapTypeStandard;
for (Customer *customer in customers) {
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
NSString *customerAddress = [Customer getWholeAddressOfCustomer:customer];
NSString *color = @"";
if([customer.status isEqualToString:@"1"])
{
color = @"Green";
}else if ([customer.status isEqualToString:@"2"]) {
color = @"Yellow";
}else if ([customer.status isEqualToString:@"3"])
{
color = @"Red";
}else {
color = customer.status;
}
[geoCoder geocodeAddressString:customerAddress completionHandler:^(NSArray *placemarks, NSError *error)
{
[NSThread sleepForTimeInterval:0.25];
if (placemarks.count == 0)
{
NSLog(@"No place for customer %@ was found",customerAddress);
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if(placemark.location.coordinate.latitude != 0.000000 && placemark.location.coordinate.longitude != 0.000000)
{
CustomerAnnotation *annotation = [[CustomerAnnotation alloc]initWithCoordinate:placemark.location.coordinate andName:customer.name andNumber:customer.customerNo andColor:color];
[self.mapAnnotations addObject:annotation];
}
}];
}
CLLocationDegrees totalLatitude=0;
CLLocationDegrees totalLongitude = 0;
for (int i=0; i < [self.mapAnnotations count]; i++) {
totalLatitude += [(CustomerAnnotation *)[self.mapAnnotations objectAtIndex:i] coordinate].latitude;
totalLongitude += [(CustomerAnnotation *)[self.mapAnnotations objectAtIndex:i] coordinate].longitude;
[self.mapView addAnnotation:[self.mapAnnotations objectAtIndex:i]];
}
MKCoordinateRegion focusRegion;
focusRegion.center.latitude = totalLatitude/[self.mapAnnotations count];
focusRegion.center.longitude = totalLongitude/[self.mapAnnotations count];
focusRegion.span.latitudeDelta = 20; //will modify this parameter later to self adapt the map
focusRegion.span.longitudeDelta = 20;
[self.mapView setRegion:focusRegion animated:YES];
但问题是时间问题,如This problem
在获取那些地方标记之前执行setRegion。在该链接的解决方案中,我应该在完成块中调用一个方法。但是这个解决方案不适合多地址问题,因为我需要在setRegion之前将所有地方标记添加到我的方法中。
无论如何在从geocodeAddressString获取所有结果后执行方法?
提前致谢。
答案 0 :(得分:0)
问题已解决。
在块之外,我使用计数器记录添加的注释。
__block int customerCount = 0;
当此计数等于整数时,自动聚焦所有客户的中心区域。
if (customerCount == [customers count]) {
//Set the focus
}