我需要使用CLGeocoder,而不是 Google API对大量地址进行地理编码。
我的问题是我的代码只为下面数组中的第一个地址添加了注释。但是,函数被调用适当的次数 - 在为所有地址调用函数之后,块只运行第一个地址:
- (void)mapPoints {
NSString *foo = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"names%d", self.indexOfSchool] ofType:@"plist"];
NSArray *description = [NSArray arrayWithContentsOfFile:foo];
NSString *bar = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d1", self.indexOfSchool] ofType:@"plist"];
NSArray *details = [NSArray arrayWithContentsOfFile:bar];
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d0", self.indexOfSchool] ofType:@"plist"];
NSArray *addresses = [NSArray arrayWithContentsOfFile:path];
self.saved = [NSMutableArray alloc] init];
for (int q = 0; q < addresses.count; q+= 20) {
[self annotate:[addresses objectAtIndex:q] detail:[details objectAtIndex:q] andDesc:[description objectAtIndex:q]];
}
}
see updated annotate: method below...
以下是我的日志显示方式:
here
here
here
here
.
..
...
....
<MKPointAnnotation: 0x16fc12e0>
因此,尽管使用循环调用该函数,但该块不会针对除第一个之外的任何结果运行。
我知道我的地址很好。这对于函数的任何数量(> 1)调用都不起作用。
循环中的+= 20
与仅绘制一个点无关:这对++
也不起作用(也有大约200个结果)。
我对块很新,所以希望这是一个简单的解决方案。非常感谢任何帮助!
修改 改为:
- (void)annotate:(NSString *)address detail:(NSString *)detail andDesc:(NSString *)description {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:address
completionHandler:^(NSArray* placemarks, NSError* error) {
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = description;
point.subtitle = [NSString stringWithFormat:@"%@ miles from origin", detail];
MKCoordinateRegion region = self.directionsView.region;
region.center = [(CLCircularRegion *)placemark.region center];
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
[self.directionsView addAnnotation:point];
NSLog(@"%@", point);
[self.directionsView setRegion:region animated:YES];
}
}
];
[self.saved addObject:geocoder];
NSLog(@"%@", geocoder);
}
...仍然会拉出一张没有注释的空白地图 - 甚至不是第一个。每次调用函数时,地理编码器阵列都有不同的内存地址,因此该部分似乎正在工作。
答案 0 :(得分:5)
你连续几次调用geocodeAddressString,但苹果的文档说
启动转发地理编码请求后,请勿尝试 启动另一个正向或反向地理编码请求。
所以我认为正在发生的事情是当你创建一个新请求时取消当前请求,或者如果一个新请求已在进行中,则忽略所有新请求。
作为一种解决方法,您可以对一个点进行地理编码,然后对完成块中的下一个点进行地理编码或创建地理编码器的多个实例
答案 1 :(得分:3)
每个CLGeocoder
对象一次只能处理一个请求。尝试在CLGeocoder
方法中创建新的annotate
对象,而不是重用存储在属性中的单个对象。只要你启用了ARC,你应该没问题。
请注意,Apple可能会限制您发送到其服务器的同时请求数量,因此如果您执行了大量请求,则可能需要限制未完成请求的数量。
答案 2 :(得分:1)
无论您拥有多少CLGeocoder
个实例,一次只能运行一个地理编码请求。您必须从前一个请求的完成块开始另一个请求。
另外,请注意,在短时间内对太多地址进行地理编码将达到其内部限制。在我的实验中,在约50个请求(一个接一个)之后,框架拒绝处理下一个约60秒的新请求。
答案 3 :(得分:-2)
这是一个Xamarin伪代码,但它应该在本机中使用相同的方式,因为我必须首先转换为C#:
forloop()
{
var geocoder = new CLGeocoder();
var placemarks = await geocoder.GeocodeAddressAsync(address);
}