我正在向 Google 查询地图视图的纬度/经度点。这可能需要很长时间,具体取决于用户在应用程序中输入了多少地址,因为地图会查看所有地址。我还在for
循环中的查询之间引入了一个短暂的延迟,以确保谷歌给我很好的结果(如果你查询得太快,它不会给你有效的纬度/经度点,而是 0,0)。
因为这需要很长时间,一旦用户按下按钮进入这个UIViewController
需要很长时间,我担心用户会认为应用程序坏了。理想情况下,我希望 ViewController “显示”,但有一个地图(最初没有注释),在地图上带有一个动画活动指示器,直到它完成查询,然后加载注释。这样,用户可以在等待地图加载时查看视图上的其他信息。
这是我的代码:
- (void) viewDidLoad {
[mapScroll startAnimating]; // activity indicator outlet
[self makeMap];
// ... etc.
}
- (void)makeMap {
allRegions = [[NSMutableArray alloc] init];
[self getDistinctRegions]; //generates allRegions array
double maxLat = -90;
double maxLon = -180;
double minLat = 90;
double minLon = 180;
for (int i=0; i<[allRegions count]; i++) {
NSString *tempString = [allRegions objectAtIndex:i];
NSString *searchString = [tempString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *queryURL = [[NSString alloc] initWithFormat:@"http://maps.google.com/maps/geo?output=csv&q=%@",searchString];
NSString *queryResults = [[NSString alloc] initWithContentsOfURL: [NSURL URLWithString:queryURL] encoding: NSUTF8StringEncoding error:nil];
NSArray *queryData = [queryResults componentsSeparatedByString:@","];
if ([queryData count] == 4) {
double latitude = [[queryData objectAtIndex:2] doubleValue];
double longitude = [[queryData objectAtIndex:3] doubleValue];
if (latitude > maxLat) maxLat = latitude;
if (latitude < minLat) minLat = latitude;
if (longitude > maxLon) maxLon = longitude;
if (longitude < minLon) minLon = longitude;
CLLocationCoordinate2D coordinate;
coordinate.latitude = latitude;
coordinate.longitude = longitude;
MKPlacemark *marker;
marker = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
[mapView addAnnotation:marker];
NSLog(@"%d",i);
[NSThread sleepForTimeInterval:0.12];
}
}
MKCoordinateRegion overallRegion;
double latSpan = abs(maxLat - minLat);
double lonSpan = abs(maxLon - minLon);
double avgLatitude = (maxLat+minLat)/2;
double avgLongitude = (maxLon+minLon)/2;
overallRegion.center.latitude = avgLatitude;
overallRegion.center.longitude = avgLongitude;
overallRegion.span.latitudeDelta = latSpan;
overallRegion.span.longitudeDelta = lonSpan;
[mapView setRegion:overallRegion animated:YES];
[mapScroll stopAnimating];
mapScroll.hidden = TRUE;
}