Objective-C – 根据用户输入的查询搜索街道
我想允许用户搜索街道名称并将结果显示在UITableView中.
目前该地区并不重要,它可以来自任何地区. 我在搜索中找不到任何相关示例,我不知道是否应该使用CLLocation或MKLocalSearch. 根据文档,我应该使用MKLocalSearch:
但我尝试了两种方法,它只给我1个结果(即使 – 虽然有一个NSArray返回. 这是CLGeocoder方法: CLGeocoder *geocoding = [[CLGeocoder alloc] init]; [geocoding geocodeAddressString:theTextField.text completionHandler:^(NSArray *placemarks,NSError *error) { if (error) { NSLog(@"%@",error); } else { NSLog(@"%i",[placemarks count]); for(CLPlacemark *myStr in placemarks) { NSLog(@"%@",myStr); } } }]; 这是我的MKLocalSearch尝试: MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init]; request.naturalLanguageQuery = theTextField.text; request.region = self.region; localSearch = [[MKLocalSearch alloc] initWithRequest:request]; [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response,NSError *error){ if (error != nil) { [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Map Error",nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show]; return; } if ([response.mapItems count] == 0) { [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Results",nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show]; return; } self.streets = response; [self.streetsTableView reloadData]; }]; 在某些情况下,MKLocalSearch似乎返回了超过1个响应,但这些与非街道名称搜索的地方有关. 提前致谢. 解决方法
这是我能得到的最接近的.这涉及使用
google places API Web Service.
注意:您可以使用他们的Google Maps API等.我相信还有其他方法可以从各种Google API获取此信息. NSURL *googlePlacesURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&location=%f,%f&sensor=true&key=API_KEY",formattedSearchText,location.coordinate.latitude,location.coordinate.longitude]]; 响应是JSON对象.将其转换为字典. NSDictionary *response = [NSJSONSerialization JSONObjectWithData:_googlePlacesResponse options:NSJSONReadingMutableContainers error:&error]; if([[response objectForKey:@"status"] isEqualToString:@"OK"]) { NSArray *predictions = [response objectForKey:@"predictions"]; for(NSDictionary *prediction in predictions) { NSArray *addressTypes = [prediction objectForKey:@"types"]; if([addressTypes containsObject:@"route"]) { //This search result contains a street name. //Now get the street name. NSArray *terms = [prediction objectForKey:@"terms"]; NSDictionary *streetNameKeyValuePair = [terms objectAtIndex:0]; NSLog(@"%@",[streetNameKeyValuePair objectForKey@"value"]); } } } 可能的类型似乎是 >路线 – >街道名称 您可以使用仅包含路由作为地址类型的预测来填充表视图.这可行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |