Search code examples
iosmkmapviewios-simulatorgeocodingclgeocoder

Forward GeoCoding is Working on Simulator but not iPhone


So I have a simple application that passes an address as a string to a view which then uses

    - (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;
}

and that works great— on the simulator. As soon as I load it on to my phone, the coordinate of the pin I place is no longer at the lat/long of the address, but instead is 0,0.

What's going on? Thanks in advance.


Solution

  • Change your method like this:

     - (CLLocationCoordinate2D)geoCodeUsingAddress:(NSString *)address
        {
            double latitude = 0, longitude = 0;
            NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *req = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false", esc_addr];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
            NSError *err = nil;
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
    
            if (!err)
            {
                NSLog(@"status = %@",[jsonDict objectForKey:@"status"]);
                if ([[jsonDict objectForKey:@"status"] isEqualToString:@"OK"])
                {
                    latitude = [[[[[[jsonDict objectForKey:@"results"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lat"] doubleValue];
                    longitude = [[[[[[jsonDict objectForKey:@"results"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lng"] doubleValue];
                }
            }
    
            CLLocationCoordinate2D center;
            center.latitude = latitude;
            center.longitude = longitude;
            return center;
        }