Отображение ближайших ресторанов в MKMap View
В моем приложении для iphone я должен показать ближайшие рестораны в виде карты, в настоящее время я использую url Google map в веб-представлении.
Но как я могу показать близлежащие рестораны с текущим местоположением в 5000 метров с собственным видом MKMap (я узнал свое текущее местоположение-lat&long)
Я хотел бы узнать, как реализовать, как показано на следующем снимке экрана (нажав аннотации, перейдя к его деталям тоже)
Какая-нибудь помощь ?? заранее спасибо
3 ответа:
В iOS 6.1 вы можете использовать
MKLocalSearch
, часть стандартного iOS MapKit.рамки:MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init]; request.naturalLanguageQuery = @"restaurant"; request.region = mapView.region; MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request]; [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) { NSMutableArray *annotations = [NSMutableArray array]; [response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop) { CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithPlacemark:item.placemark]; annotation.title = item.name; annotation.subtitle = item.placemark.addressDictionary[(NSString *)kABPersonAddressStreetKey]; annotation.phone = item.phoneNumber; [annotations addObject:annotation]; }]; [self.mapView addAnnotations:annotations]; }];
Моя пользовательская аннотация-это просто
MKPlacemark
плюс заголовок и подзаголовок:@interface CustomAnnotation : MKPlacemark @property (strong, nonatomic) NSString *title; @property (strong, nonatomic) NSString *subtitle; @property (strong, nonatomic) NSString *phone; @end
Если вы хотите видеть индикатор раскрытия на своем выноске (чтобы вы могли перейти к другому контроллеру для просмотра деталей, вы можете:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if (![annotation isKindOfClass:[CustomAnnotation class]]) return nil; MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotationView"]; annotationView.canShowCallout = YES; annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return annotationView; }
Если вы хотите открыть другой вид, когда пользователь нажимает на выноску аксессуара:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control { if (![view.annotation isKindOfClass:[CustomAnnotation class]]) return; CustomAnnotation *annotation = (CustomAnnotation *)view.annotation; ABRecordRef person = ABPersonCreate(); ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef) annotation.title, NULL); if (annotation.phone) { ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) annotation.phone, kABPersonPhoneMainLabel, NULL); ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil); CFRelease(phoneNumberMultiValue); } ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); ABMultiValueAddValueAndLabel(address, (__bridge CFDictionaryRef) annotation.addressDictionary, kABWorkLabel, NULL); ABRecordSetValue(person, kABPersonAddressProperty, address, NULL); ABUnknownPersonViewController *personView = [[ABUnknownPersonViewController alloc] init]; personView.unknownPersonViewDelegate = self; personView.displayedPerson = person; personView.allowsAddingToAddressBook = YES; [self.navigationController pushViewController:personView animated:YES]; CFRelease(address); CFRelease(person); } - (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownPersonView didResolveToPerson:(ABRecordRef)person { }
Для получения дополнительной информации (например, настройка аннотации просмотры, определение местоположения устройства и т.д.), обратитесь к руководствупо программированию определения местоположения .
См. https://github.com/robertmryan/MKMapView-custom-annotations для простого примера.
Сначала обратитесь к этой ссылке Google API https://developers.google.com/places/documentation/search а затем получить id и добавить это в параметр googleId и просто установить radious параметр со значением 5000 и для типов установить значение ресторан..
Смотрите мой пример ниже..
NSString *str=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=5000&types=%@&sensor=false&key=%@",currentLocation.latitude,currentLocation.longitude,@"restaurant",@"AIzaSyB7YTFTYyk9eb8ULNGxoy06-b_0DUOqdrY"]; NSLog(@"\n\n URL %@",str); NSURL *strurl=[NSURL URLWithString:[str stringByReplacingOccurrencesOfString:@"|" withString:@"%7C"]]; // NSURL *strurl = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyB7YTFTYyk9eb8ULNGxoy06-b_0DUOqdrY"]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:strurl]; [request setDelegate:self]; [request startAsynchronous];
И реализовать всю эту запись на
MKMapView
, Как ниже...- (void)requestFinished:(ASIHTTPRequest *)request { // Use when fetching text data NSString *responseString = [request responseString]; NSLog(@"\n\n>>>>......Response String >>> %@",responseString); if(responseString) { SBJSON *json = [[SBJSON alloc] init]; NSError *error = nil; id result = [json objectWithString:responseString error:&error]; if ([result isKindOfClass:[NSMutableArray class]]) { NSLog(@"\n\n.......This is Mutable Array"); } else { if ([[result objectForKey:@"results"] count]>0) { NSLog(@">>>>>>>> dict keys :%d \nFull Address : %@\n LatLong : %@ \n total result : %d", [[result objectForKey:@"results"] count],[[result objectForKey:@"results"]valueForKey:@"vicinity"],[[[result objectForKey:@"results"]valueForKey:@"geometry"]valueForKey:@"location"],[[result objectForKey:@"results"]count]); for (int i=0; i<[[result objectForKey:@"results"] count]; i++) { ann = [[MyAnnotation alloc] init]; ann.title = [[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"name"]; ann.subtitle = [[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"vicinity"]; ann.annReferance=[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"reference"]; CLLocationCoordinate2D location; location.latitude = [[[[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"geometry"]valueForKey:@"location"] valueForKey:@"lat"]doubleValue]; location.longitude = [[[[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"geometry"]valueForKey:@"location"] valueForKey:@"lng"] doubleValue]; ann.coordinate=location; ann.annLocation=[NSString stringWithFormat:@"%f,%f",location.latitude,location.longitude]; // NSLog(@"\n\n rating %@",ann.annrating); if ([[[[result objectForKey:@"results"]objectAtIndex:i] allKeys] containsObject:@"rating"]) { // contains key ann.annrating=[[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"rating"]stringValue]; NSLog(@"\n\n rating %@",ann.annrating); } else { ann.annrating=@""; } ann.annaddress=[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"vicinity"]; [mapView addAnnotation:ann]; } } } } }
Это код, который я использую в своем приложении, просто внесите некоторые изменения с вашим требованием и вы получите результат..
Я надеюсь, что это поможет вам...