Skip to content

Instantly share code, notes, and snippets.

@robertBojor
Created February 13, 2015 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertBojor/647cf23f04eade4bf9d1 to your computer and use it in GitHub Desktop.
Save robertBojor/647cf23f04eade4bf9d1 to your computer and use it in GitHub Desktop.
Synchronous reverse GeoCoding using Google Maps API
//
// RBRevGeo.h
// RevGeo
//
// Created by Robert Bojor on 13/02/15.
// Copyright (c) 2015 Robert Bojor. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface RBRevGeo : NSObject
+ (NSString *)getKey:(NSString *)desiredKey withLat:(float)fLat andLong:(float)fLong;
@end
//
// RBRevGeo.m
// RevGeo
//
// Created by Robert Bojor on 13/02/15.
// Copyright (c) 2015 Robert Bojor. All rights reserved.
//
#import "RBRevGeo.h"
@implementation RBRevGeo
+ (NSString *)getKey:(NSString *)desiredKey withLat:(float)fLat andLong:(float)fLong
{
NSString *googleURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true", fLat, fLong];
NSString *desiredResult = @"";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:googleURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *GoogleResponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
if (requestError) {
// An error occured - Not found
desiredResult = @"Not found";
}
if ((long)[(NSHTTPURLResponse *)urlResponse statusCode] == 200) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:GoogleResponse options:NSJSONReadingAllowFragments error:nil];
if ([json[@"status"] isEqualToString:@"OK"] && [json[@"results"] count]) {
for(NSDictionary *addressResult in json[@"results"]) {
if ([addressResult[@"address_components"] count] && [desiredResult isEqualToString:@""]) {
for(NSDictionary *addressComponent in addressResult[@"address_components"]) {
if ([addressComponent[@"types"] count] && [desiredResult isEqualToString:@""]) {
for (NSString *addressType in addressComponent[@"types"]) {
if ([addressType isEqualToString:desiredKey] && [desiredResult isEqualToString:@""]) {
desiredResult = addressComponent[@"long_name"];
}
}
}
}
}
}
}
} else {
desiredResult = @"Not found!";
}
return desiredResult;
}
@end
//
// ViewController.m
// RevGeo
//
// Created by Robert Bojor on 13/02/15.
// Copyright (c) 2015 Robert Bojor. All rights reserved.
//
#import "ViewController.h"
#import "RBRevGeo.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *neighbourhood = [RBRevGeo getKey:@"neighborhood" withLat:44.212599 andLong:28.623156];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment