【问题标题】:Get latitude and longitude based on Address using Geocoder class in iOS在 iOS 中使用 Geocoder 类根据地址获取经纬度
【发布时间】:2014-08-21 14:33:40
【问题描述】:

我根据经度和纬度值获得了当前位置,然后我还使用注释在谷歌地图上获得了多个位置。现在我想根据地址(即街道、城市和县)获取经度和纬度值。需要一些关于如何实现这一点的指导。

到目前为止,这是我尝试过的:-

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize streetField = _streetField, cityField = _cityField, countryField = _countryField, fetchCoordinatesButton = _fetchCoordinatesButton, nameLabel = _nameLabel, coordinatesLabel = _coordinatesLabel;
@synthesize geocoder = _geocoder;


- (void)viewDidLoad
{

    [super viewDidLoad];
    _streetField.delegate=self;
    _cityField.delegate=self;
    _countryField.delegate=self;

    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)fetchCoordinates:(id)sender {
    NSLog(@"Fetch Coordinates");
    if (!self.geocoder) {
          NSLog(@"Geocdoing");
        self.geocoder = [[CLGeocoder alloc] init];
    }

    NSString *address = [NSString stringWithFormat:@"%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text];
    NSLog(@"GET Addres%@",address);

    self.fetchCoordinatesButton.enabled = NO;

    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
          NSLog(@"Fetch Gecodingaddress");
        if ([placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];

             NSLog(@"GET placemark%@",placemark);

            CLLocation *location = placemark.location;

            NSLog(@"GET location%@",location);

            CLLocationCoordinate2D coordinate = location.coordinate;


            self.coordinatesLabel.text = [NSString stringWithFormat:@"%f, %f", coordinate.latitude, coordinate.longitude];

            NSLog(@"CoordinatesLabel%@",self.coordinatesLabel.text);


            if ([placemark.areasOfInterest count] > 0) {
                NSString *areaOfInterest = [placemark.areasOfInterest objectAtIndex:0];
                self.nameLabel.text = areaOfInterest;
                NSLog(@"NameLabe%@",self.nameLabel.text);
            }
        }

        self.fetchCoordinatesButton.enabled = YES;
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
@end

以上代码无法为我提供纬度和经度。需要一些帮助来了解我在这里做错了什么,或者我是否遗漏了什么。

提前致谢。

【问题讨论】:

  • 使用这个链接是希望你stackoverflow.com/questions/21595538/…
  • @Anbu.Karthik 我需要根据地址获取经度和纬度值。您的代码基于邮政编码。我试过你的代码我将我的城市名称和国家名称传递给 url 但它不起作用请给我任何想法

标签: ios iphone objective-c geocoding


【解决方案1】:

这是非常老的答案,请检查新的更新

编辑

在对 iOS8 更新使用此检查之前

NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription

这用于获取基于经纬度的用户区域,例如街道名称、州名、国家/地区。

-(CLLocationCoordinate2D) getLocationFromAddressString: (NSString*) addressStr {
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [addressStr 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;
    NSLog(@"View Controller get Location Logitute : %f",center.latitude);
    NSLog(@"View Controller get Location Latitute : %f",center.longitude);
    return center;
    
}

根据你的项目在 viewdidload 方法或某处调用这样的方法

[self getLocationFromAddressString:@"chennai"];

只需在浏览器中传递这个 http://maps.google.com/maps/api/geocode/json?sensor=false&address=chennai

你会得到带有 lat 和 lon 的 json 格式

http://maps.google.com/maps/api/geocode/json?sensor=false&address=@"your city name here"




 NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text];

这个方法的用法....

CLLocationCoordinate2D center;
        center=[self getLocationFromAddressString:@"uthangarai"];
      double  latFrom=&center.latitude;
      double  lonFrom=&center.longitude;

  NSLog(@"View Controller get Location Logitute : %f",latFrom);
        NSLog(@"View Controller get Location Latitute : %f",lonFrom);

【讨论】:

  • .and 会有一个 json 格式,它显示你的城市,国家的格式化地址
  • 我得到但它没有得到确切的位置,例如 chennai(13.0839° N, 80.2700° E) 但是当运行此代码时它显示 (13.233954 80.332361)
  • 它会根据当前位置自动更改纬度和经度值
  • @karithikeyan 我正在检查模拟器
  • 它给了我正确的纬度,但是当我在地图上申请时,它会转到其他位置,请帮助...
【解决方案2】:

寻找 Swift 2.0 解决方案的人可以使用以下方法:

let address = "1 Infinite Loop, CA, USA"
        let geocoder = CLGeocoder()

        geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
            if((error) != nil){
                print("Error", error)
            }
            if let placemark = placemarks?.first {
                let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                coordinates.latitude
                coordinates.longitude
                print("lat", coordinates.latitude)
                print("long", coordinates.longitude)


            }
        })

【讨论】:

    【解决方案3】:

    试试这个,

    NSString *address = [NSString stringWithFormat:@"%@,%@,%@", self.streetField.text, self.cityField.text,self.countryField.text];    
    
    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if(!error)
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             NSLog(@"%f",placemark.location.coordinate.latitude);
             NSLog(@"%f",placemark.location.coordinate.longitude);
             NSLog(@"%@",[NSString stringWithFormat:@"%@",[placemark description]]);
         }
         else
         {
             NSLog(@"There was a forward geocoding error\n%@",[error localizedDescription]);
         }
     }
     ];
    

    【讨论】:

    • 我没有得到纬度和经度
    • 我来了,或者尝试使用 google api "maps.googleapis.com/maps/api/geocode/…"。通过将空格替换为 + 到上述 api 并解析 JSON 响应来附加您的地址字符串
    【解决方案4】:

    斯威夫特

    public func getLocationFromAddress(address : String) -> CLLocationCoordinate2D {
            var lat : Double = 0.0
            var lon : Double = 0.0
    
            do {
    
                let url = String(format: "https://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", (address.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!))
                let result = try Data(contentsOf: URL(string: url)!)
                let json = JSON(data: result)
    
                lat = json["results"][0]["geometry"]["location"]["lat"].doubleValue
                lon = json["results"][0]["geometry"]["location"]["lng"].doubleValue
    
            }
            catch let error{
                print(error)
            }
    
            return CLLocationCoordinate2D(latitude: lat, longitude: lon)
        }
    

    我使用了SwiftyJSON,但您可以根据需要解析 JSON 响应

    【讨论】:

      【解决方案5】:
      - (IBAction)forwardButton:(id)sender
      {
          if([self.address.text length])
          {
              NSString *place = self.address.text;
              CLGeocoder *geocoder = [[CLGeocoder alloc] init];
              __unsafe_unretained RTGeoCoderViewController *weakSelf = self;
              [geocoder geocodeAddressString:place completionHandler:^(NSArray* placemarks, NSError* error)
               {
                   NSLog(@"completed");
                   if ( error )
                   {
                       NSLog(@"error = %@", error );
                       dispatch_async(dispatch_get_main_queue(),
                                      ^{
                                          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[self errorMessage:error.code] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                                          [alert show];
                                      });
                   }
                   else
                   {
                      NSLog(@"%@",placemarks);
                   }
               }];
          }
      }
      

      【讨论】:

        【解决方案6】:

        试试这个

         - (void)getAddressFromAdrress:(NSString *)address withCompletationHandle:(void (^)(NSDictionary *))completationHandler {   
        
        
                        CLGeocoder *geoCoder = [[CLGeocoder alloc] init];  
                    //Get the address through geoCoder  
                    [geoCoder geocodeAddressString:address   completionHandler:^(NSArray *placemarks, NSError *error) {  
        
        
                        if ([placemarks count] > 0 && !error) {
        
                            //get the address from placemark
                            CLPlacemark *placemark = [placemarks objectAtIndex:0];
                            NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
                            CLLocation *location = placemark.location;
                            CLLocationCoordinate2D coordinate = location.coordinate;
                            _latitudeUserLocation  = coordinate.latitude;
                            _longitudeUserLocation = coordinate.longitude;
                            NSString *postalCode   =  placemark.addressDictionary[(NSString*)kABPersonAddressZIPKey];
                            if (postalCode == nil) postalCode = @"";
                            if (locatedAt == nil)  locatedAt  = @"";
                            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                        postalCode               ,kPostalCode,
                                                        locatedAt                ,kFullAddress,
                                                        nil];
                            completationHandler(dictionary);
        
                        } else {
        
                            completationHandler(nil);
                        }
                    }];
        }
        

        【讨论】:

          猜你喜欢
          • 2014-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-02
          • 1970-01-01
          • 2013-07-04
          • 2014-06-14
          相关资源
          最近更新 更多