Reputation: 161
I am following this tutorial : http://www.raywenderlich.com/13160/using-the-google-places-api-with-mapkit, but for some reason my app is returning:
Google Data: ( )
Here is my .h file:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kGOOGLE_API_KEY @"API PLACED HERE, LEFT BLANK FOR STACKOVERFLOW"
@interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocationCoordinate2D currentCentre;
int currenDist;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@end
and my implementation file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Make this controller the delegate for the map view.
self.mapView.delegate = self;
// Ensure that you can view your own location in the map view.
[self.mapView setShowsUserLocation:YES];
//Instantiate a location object.
locationManager = [[CLLocationManager alloc] init];
//Make this controller the delegate for the location manager.
[locationManager setDelegate:self];
//Set some parameters for the location object.
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)toolBarButtonPress:(UIBarButtonItem *)sender {
UIBarButtonItem *button = (UIBarButtonItem *)sender;
NSString *buttonTitle = [button.title lowercaseString];
[self queryGooglePlaces:buttonTitle];
}
-(void) queryGooglePlaces: (NSString *) googleType {
NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json? location=%f,%f&radius=%@&types=%@&sensor=true&key=%@", currentCentre.latitude, currentCentre.longitude, [NSString stringWithFormat:@"%i", currenDist], googleType, kGOOGLE_API_KEY];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", url);
//Formulate the string as a URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:@"results"];
//Write out the data to the console.
NSLog(@"Google Data: %@", places);
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
//Get the east and west points on the map so you can calculate the distance (zoom level) of the current map view.
MKMapRect mRect = self.mapView.visibleMapRect;
MKMapPoint eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect));
MKMapPoint westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect));
//Set your current distance instance variable.
currenDist = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint);
//Set your current center point on the map instance variable.
currentCentre = self.mapView.centerCoordinate;
}
#pragma mark - MKMapViewDelegate methods.
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views {
MKCoordinateRegion region;
region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate,1000,1000);
[mv setRegion:region animated:YES];
}
@end
My console log of the final formatted URL is :
https://maps.googleapis.com/maps/api/place/search/json? location=HIDDENLAT,HIDDENLONG&radius=995&types=bar&sensor=true&key=HIDDENAPI
I have replaced the generated lat, long and API values above but they were returned as the correct values?
Another SO answer I found said to add the:
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
which I did but this has not worked for me?
Why isn't this working?
Upvotes: 2
Views: 3588
Reputation: 1038
This could be a number of issues including your API key, your search radius, or your search "type", or a JSON parsing problem. However, the code should go exactly as Gary Stewart has it posted above. He even helped me find my answer just by asking the question...
Add NSLog(@"%@", url);
after the URL string in the queryGooglePlaces methord as he does above. This logs the URL request to your console so you can ensure it's being compiled as expected. If it is but you're STILL not getting data back, then copy the URL you generated from your console and open it in a web browser. At the bottom of the generated page, it will tell you why you're not getting data.
From Google's Developer Documentation:
The "status" field within the search response object contains the status of the request, and may contain debugging information to help you track down why the request failed. The "status" field may contain the following values:
OK indicates that no errors occurred; the place was successfully detected and at least one result was returned. ZERO_RESULTS indicates that the search was successful but returned no results. This may occur if the search was passed a latlng in a remote location. OVER_QUERY_LIMIT indicates that you are over your quota. REQUEST_DENIED indicates that your request was denied, generally because of lack of a sensor parameter. INVALID_REQUEST generally indicates that a required query parameter (location or radius) is missing.
My problem was that I was sending a search "type" of "breakfast" rather than simply "food". Silly me, "breakfast" would be a keyword, not a type.
(Here's a list of supported types by the way: https://developers.google.com/places/documentation/supported_types)
Upvotes: 2
Reputation: 2399
Change
@"https://maps.googleapis.com/maps/api/place/search/json? location=%f,%f&radius=%@&types=%@&sensor=true&key=%@"
to
@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%@&types=%@&sensor=true&key=%@"
(ie, no space after the ? in the url template string)
Upvotes: 1