0

我只有几个月的 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];

但问题是像 这个问题这样的时间问题

setRegion 在获得这些地点标记之前执行。在该链接提出的解决方案中,我应该在完成块中调用一个方法。但是此解决方案不适合多地址问题,因为我需要在 setRegion 之前将所有地点标记添加到我的方法中。

从 geocodeAddressString 获取所有结果后,是否有办法执行方法?

提前致谢。

4

1 回答 1

0

问题解决了。

在块之外,我使用了一个计数器来记录添加的注释。

__block int customerCount = 0; 

当此计数等于整数时,自动聚焦所有客户的中心区域。

if (customerCount == [customers count]) {
   //Set the focus
}
于 2012-09-05T08:57:19.533 回答