使用IOS中的Geocoder类,基于zip获取经度和纬度

时间:2014-02-06 06:22:15

标签: ios iphone objective-c geocoding

我根据经度和纬度值得到了当前位置 然后我还使用Annotation在谷歌地图上获得了多个位置 现在我想根据邮政编码获取经度和纬度值 我不知道如何根据邮政编码获得经度和纬度值

3 个答案:

答案 0 :(得分:16)

这是调用google map api进行地理编码的方法,如果您通过Zipcode / Postal代码,则会得到结果

-(void)ViewDidLoad
{ 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@",yourzipcodetext/PostalcodeText.text]]];

[request setHTTPMethod:@"POST"];

NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];

NSString *lataddr=[[[[[dict objectForKey:@"results"] objectAtIndex:0]objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lat"];

NSString *longaddr=[[[[[dict objectForKey:@"results"] objectAtIndex:0]objectForKey:@"geometry"]objectForKey:@"location"]objectForKey:@"lng"];


NSLog(@"The resof latitude=%@", lataddr);

NSLog(@"The resof longitude=%@", longaddr);


}

<强> Chioce-2

CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder geocodeAddressString:@"ZIP CODE HERE" completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        CLLocation *location = placemark.location;
        CLLocationCoordinate2D coordinate = location.coordinate;
        NSLog(@"Latitude %f", coordinate.latitude);
        NSLog(@"Longitude %f", coordinate.longitude);
    }];

答案 1 :(得分:11)

就像这样简单:

CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder geocodeAddressString:@"ZIP CODE HERE" completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        CLLocation *location = placemark.location;
        CLLocationCoordinate2D coordinate = location.coordinate;
        NSLog(@"Latitude %f", coordinate.latitude);
        NSLog(@"Longitude %f", coordinate.longitude);
    }];

答案 2 :(得分:1)

Apple在forward geocoding上发布了可以帮助您的好文档。