私のiPhoneアプリでは、マップビューで近くのレストランを表示する必要があります.現在、WebビューでGoogleマップのURLを使用しています.
しかし、ネイティブの MKMap ビューで現在地から 5000 メートル以内にある近くのレストランを表示するにはどうすればよいですか (現在地の緯度と経度がわかりました)。
以下のスクリーンショットのように実装する方法を学びたいと思います(詳細に移動する注釈をクリックすることもできます)
何か役に立ちますか?? 前もって感謝します
MKLocalSearch
iOS 6.1 では、標準の iOS MapKit.framework の一部であるを使用できます。
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];
}
}
}
}
}
これは私のアプリケーションで使用するコードです。要件を変更するだけで、出力が得られます..
これがお役に立てば幸いです...