我使用谷歌地理编码Svc从地址获取Lat和Lng,有时候谷歌地理编码Svc失败(因为每秒或每天的toomany计数),所以我想使用Apple提供的Default Geocoder Svc。
请参阅此处我的代码
-(void)getLatandlongfromAddress
{
CLLocationCoordinate2D Coordinate=[self geoCodeUsingAddress:@"orlando"];
}
- (CLLocationCoordinate2D)geoCodeUsingAddress:(NSString *)address
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
NSError *err = nil;
NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
if (!err)
{
NSLog(@"status = %@",[jsonDict objectForKey:@"status"]);
if ([[jsonDict objectForKey:@"status"] isEqualToString:@"OK"])
{
//If status is cmng Im returned lat and long
}
else
{
// I want to use geocode Svc
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"Orlando 32835" completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSLog(@"%@",placemarks);
CLPlacemark *placemark = [placemarks lastObject];
}
}];
}
}
}
指导我任何想法,谢谢..
答案 0 :(得分:1)
您的代码中存在多个错误:
[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
并将kNilOptions
作为选项参数传递,则不会收回可变字典但不可变字典。这是您更正后的代码(包括完成处理程序):
- (CLLocationCoordinate2D)geoCodeUsingAddress:(NSString *)address completionHandler:(void (^)(CLLocation *location, NSError *error))completionHandler {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]]; // Whatever `req` is...
NSError *jsonError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (jsonDict) {
NSLog(@"status = %@", [jsonDict objectForKey:@"status"]);
if ([[jsonDict objectForKey:@"status"] isEqualToString:@"OK"]) {
// If status is cmng Im returned lat and long
// Get them from you local file
CLLocationDegrees latitude = 30.0;
CLLocationDegrees longitude = 50.0;
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
completionHandler(location, nil);
} else {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"Orlando 32835" completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count) {
NSLog(@"%@",placemarks);
CLPlacemark *placemark = [placemarks lastObject];
completionHandler(placemark.location, nil);
} else {
NSLog(@"%@", error);
completionHandler(nil, error);
}
}];
}
} else {
// Populate the error
completionHandler(nil, [NSError errorWithDomain:@"YOUR_DOMAIN" code:1000 userInfo:nil]);
}
}
您可以像使用完成处理程序的任何其他方法一样调用它:
[self geoCodeUsingAddress:@"Orlando 32835" completionHandler:^(CLLocation *location, NSError *error) {
if (location) {
// Use location
} else {
NSLog(@"Error: %@", error.userInfo);
}
}];