2013-02-19 13 views
8

W mojej aplikacji na iPhone'a muszę pokazać w pobliżu restauracji w widoku mapy. Obecnie korzystam z adresu URL mapy Google w widoku internetowym.Pokazywanie pobliskich restauracji w widoku MKMap

Ale jak mogę pokazać pobliskich restauracji na 5000 metrów z bieżącej lokalizacji z natywnym widzenia MKMap (I okazało się, moja obecna lokalizacja-łac & długo)

Chciałbym dowiedzieć się, jak zaimplementować jak w poniżej zrzut ekranu (klikając adnotacje przechodzące również do jego szczegółów)

Dowolna pomoc? z góry dzięki

enter image description here

+0

Googling w Google Place API – Rushabh

+0

no..Nie mówię o miejscu Google API, że jestem w stanie pokazać go na WEBView, chcę go zaimplementować na mapach iOS –

+0

http: // stackoverflow.com/questions/7387154/is-it-it-possible-for-search-for-nearby-restaurants-and-bars-via-api-for-iphone-sdk – Rushabh

Odpowiedz

14

w iOS 6.1, można użyć MKLocalSearch, część standardowego 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]; 
}]; 

Moje niestandardowe adnotacji jest tylko MKPlacemark plus tytuł i podtytuł:

@interface CustomAnnotation : MKPlacemark 

@property (strong, nonatomic) NSString *title; 
@property (strong, nonatomic) NSString *subtitle; 
@property (strong, nonatomic) NSString *phone; 

@end 

Jeśli chcesz zobaczyć wskaźnik ujawnienia na swoim objaśnieniu (możesz przejść do innego kontrolera, aby wyświetlić szczegóły, możesz:

- (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; 
} 

Jeśli chcesz otworzyć inny widok, gdy użytkownik kliknie na akcesorium objaśnienia:

- (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 
{ 

} 

Aby uzyskać więcej informacji (np dostosowywanie widoków adnotacji, określanie lokalizacji urządzenia itp.), patrz Location Awareness Programming Guide.

Zobacz prosty przykład na stronie https://github.com/robertmryan/MKMapView-custom-annotations.

+0

Dzięki zadziałało ... :) Mogę przekazać tytuł strony ze szczegółami jak poniżej, jak przekazać podtytuł? Proszę zobaczyć to pytanie http://stackoverflow.com/questions/14954240/how-to-pass-subtitle-of-annotation-in-mkmapview –

+0

@NithinMK Przekazałeś to w taki sam sposób, w jaki zdałeś tytuł. Osobiście uważam, że łatwiej jest przekazać samą adnotację, w ten sposób strona ze szczegółami może uzyskać dostęp do wszystkich właściwości adnotacji. Jeśli nadal masz problemy, opublikuj nowe pytanie za pomocą kodu, aby utworzyć adnotację, a także swój kod, aby uruchomić stronę szczegółów, a my pomożemy ci dalej. Możesz dodać link do nowego pytania tutaj, aby móc je zobaczyć po opublikowaniu. – Rob

0

użycie google api, aby uzyskać wyniki w formacie json lub xml

refer this link

+0

tak, że mogę pobrać przy użyciu tego: https: //maps.googleapis.com/maps/api/place/search/json? location = 10.009890,76.316013 & radius = 5000 & types = restaurant & sensor = false & key = AIzaSyCd_coP8f7TbdlcVavbgUku2S81pgAz_bs & pagetoken = CmRTAAAAIrTPdzdJzqNYSCw7p4D4ThGHh0srcyUpZ9LfvXRJJA1wR-DOsiXZ07V9TzdTu9HJdCwq2kRFIftm_FCzo4ofboAN95CjpX-6e41G_oXYQph5YIrP6HzM2hzrMw2G7phhEhDx6vzp9KlRo15w4Knd8L3QGhQBlsszX43YRC6Q-NbhFDcjDvu_eQ , ale jak wdrożyć te wynikają w MKMapView –

+0

konwersji json lub danych xML do tablicy i dodać adnotacje w MapView – NANNAV

+0

co biorę pod tablicę, łac długo? Czy istnieje samouczek dla wielu adnotacji? –

0

pierwsze odnoszą tego API Google link https://developers.google.com/places/documentation/search a następnie uzyskać identyfikator i dodać to w parametrze googleId i ustaw parametr radious z wartością 5000 i dla typów zestaw wartość restauracja ..

Zobacz mój ryk przykład ..

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]; 

i wdrożyć te cały rekord na MKMapView jak mieszka ...

- (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 
        { 
         [email protected]""; 
        } 
        ann.annaddress=[[[result objectForKey:@"results"]objectAtIndex:i]valueForKey:@"vicinity"]; 
        [mapView addAnnotation:ann]; 
       } 
      } 
     } 
    } 
} 

Jest to kod, który używam w moim aplikacji, po prostu zrób kilka zmian z twoim wymaganiem, a otrzymasz wydruk ..

Mam nadzieję, że ci to pomoże ...

+0

niech moja próba bro..dzięki za pomoc –

+0

Ci najbardziej przychodzą :) po prostu utwórz klasę MyAnnotation lub coś, co chcesz wyświetlić z innymi parametrami .. –

+0

, ale ... Co to jest ASIFormDataRequest ?? –