如何根据纬度和经度获取地址?

时间:2012-06-19 06:46:09

标签: iphone json

我在iPhone上获得了经纬度。但我想找到基于纬度和经度的地址。我用过Ios5。请给我源代码查找地址。我用过这段代码 .m文件

MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:Coordinate2D];

[geocoder setDelegate:self];

[geocoder start]; // put in vievdidload


-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{    
    NSLog(@"The geocoder has returned: %@", [placemark country]);
}

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"Error");
}

但它会给出消息错误。

2 个答案:

答案 0 :(得分:0)

一种方法是使用google api获取位置名称并解析xml。希望它能帮到你

//Place below parser code where you are reading latlng and place your latlng in the url

NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false"]];
[parser setDelegate:self];
[parser parse];

// Below are the delegates which will get you the exact address easyly

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{    
  if([elementName isEqualToString:@"formatted_address"]){
    got = YES; //got is a BOOL
  }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
  if(got){
    NSLog(@"the address is = %@",string);
  }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

}

//what we are doing is using xmlparser to parse the data which we get through the google map api copy above link and use in browser you will see the xml data brought

答案 1 :(得分:0)

如果您使用的是iOS5,那么这里是代码: -

CLGeocoder *geocoder = [[CLGeocoder alloc]init];
CLLocation *location = [[CLLocation alloc]initWithLatitude:10.0 longitude:10.0];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
  if(!error){
       CLPlacemark *placemark = [placemarks objectAtIndex:0];
       MKPlacemark *placemark1 = [[MKPlacemark alloc]initWithPlacemark:placemark];
       [self.mapView addAnnotation:placemark1];   //mapView is object of MKMapView
     }
}];