【问题标题】:Reverse Geocoding using google maps api iOS使用谷歌地图 api iOS 反向地理编码
【发布时间】:2015-07-27 03:08:34
【问题描述】:

我正在使用以下代码进行反向地理编码

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {   
    curLoc=newLocation;
    if (curLoc != nil) {
        latitude=curLoc.coordinate.latitude;
        longitude=curLoc.coordinate.longitude;
        //[self loadMap:latitude second:longitude];
        [self MarkerPoint:latitude+0.04 second:longitude+0.1 third:latitude-0.04 forth:longitude-0.1];

        NSError *error;
        NSString *lookupString = [NSURL URLWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",latitude,longitude]];
        NSLog(@"URL: %@",lookupString);
        lookupString = [lookupString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

        NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookupString]];

        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];

        self.locationArray = [[jsonDict valueForKey:@"results"] valueForKey:@"formatted_address"];
        int total = self.locationArray.count;
        NSLog(@"locationArray count: %d", self.locationArray.count);

        for (int i = 0; i < total; i++)
        {
            NSString *statusString = [jsonDict valueForKey:@"status"];
            NSLog(@"JSON Response Status:%@", statusString);
            NSLog(@"Address: %@", [self.locationArray objectAtIndex:i]);
        }
    }
}    

现在我收到此错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0xbce98c0'
*** First throw call stack:
(
    0   CoreFoundation                      0x034551e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x031a98e5 objc_exception_throw + 44
    2   CoreFoundation                      0x034f2243 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x0344550b ___forwarding___ + 1019
    4   CoreFoundation                      0x034450ee _CF_forwarding_prep_0 + 14
    5   MatchPoint                          0x00017fad -[ICSViewController locationManager:didUpdateToLocation:fromLocation:] + 813
    6   CoreLocation                        0x0164655e CLLocationCoordinate2DGetDistanceFrom + 18294
    7   CoreLocation                        0x01645af4 CLLocationCoordinate2DGetDistanceFrom + 15628
    8   CoreLocation                        0x01642e40 CLLocationCoordinate2DGetDistanceFrom + 4184
    9   CoreLocation                        0x0163c680 CLClientInvalidate + 996
    10  CoreFoundation                      0x034140b0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 16
    11  CoreFoundation                      0x033dd339 __CFRunLoopDoBlocks + 361
    12  CoreFoundation                      0x033fb753 __CFRunLoopRun + 2355
    13  CoreFoundation                      0x033fa9d3 CFRunLoopRunSpecific + 467
    14  CoreFoundation                      0x033fa7eb CFRunLoopRunInMode + 123
    15  GraphicsServices                    0x051f05ee GSEventRunModal + 192
    16  GraphicsServices                    0x051f042b GSEventRun + 104
    17  UIKit                               0x01e69f9b UIApplicationMain + 1225
    18  MatchPoint                          0x0001d9fd main + 141
    19  libdyld.dylib                       0x03d206d9 start + 1
    20  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

【问题讨论】:

  • 评论这一行然后检查lookupString = [lookupString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

标签: ios objective-c geocoding reverse


【解决方案1】:

尝试更改此行

NSString *lookupString = [NSURL URLWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",latitude,longitude]];

NSString *lookupString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",latitude,longitude];

【讨论】:

  • 拯救了我的一天,伙计
【解决方案2】:

提供有效的经纬度静态并先检查。成功后只使用动态经纬度

-(void)getGoogleAdrressFromLatLong : (CGFloat)lat lon:(CGFloat)lon{
    //[self showLoadingView:@"Loading.."];
    NSError *error = nil;

    NSString *lookUpString  = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&amp;sensor=false", lat,lon];

    lookUpString = [lookUpString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

    NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];

   // NSLog(@"%@",jsonDict);

    NSArray* jsonResults = [jsonDict objectForKey:@"results"];

   // NSLog(@"%@",jsonResults);

}

【讨论】:

    【解决方案3】:

    首先,locationManager: didUpdateToLocation: fromLocation: 在 iOS 6 及更高版本中已弃用。 我建议您用新方法替换此方法:locationManager: didUpdateLocations: 并使用GMSGeocoder reverseGeocodeCoordinate: completionHandler: 从二维坐标检索地址。

    我的解决方案基于使用GMSGeocoder

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.activityType = CLActivityTypeFitness;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    [self.locationManager requestWhenInUseAuthorization];// iOS 8 requirement
    [self.locationManager requestAlwaysAuthorization];// iOS 8 requirement
    
    self.locateOnCurrentPosition = YES; // Flag for changing camera once you really needed
    [self.locationManager startUpdatingLocation];
    
    #pragma mark - CLLocationManagerDelegate
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        if (self.locateOnCurrentPosition) {
            NSLog(@"CLLocationManager didUpdateLocations: %@", [locations lastObject]);
            self.locateOnCurrentPosition = NO;
            CLLocation *location = [locations lastObject];
            self.mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:16]; // GMSMapView entity
            self.mapMarker.position = self.mapView.camera.target; // GMSMarker entity
            [[GMSGeocoder geocoder] reverseGeocodeCoordinate:location.coordinate completionHandler:
            ^(GMSReverseGeocodeResponse *response, NSError *error){
                NSLog(@"Address: %@", response.firstResult);
            }];
        }
    }
    

    【讨论】:

      【解决方案4】:

      传递你的纬度和经度它会给你正确的地址...

      [[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude) completionHandler:^(GMSReverseGeocodeResponse* response, NSError* error) {
                  NSLog(@"reverse geocoding results:");
                 for(GMSAddress* addressObj in [response results])
                  {
                      NSLog(@"%@",[response results]);
      
                      NSLog(@"coordinate.latitude=%f", addressObj.coordinate.latitude);
                      NSLog(@"coordinate.longitude=%f", addressObj.coordinate.longitude);
                      NSLog(@"thoroughfare=%@", addressObj.thoroughfare);
                      NSLog(@"locality=%@", addressObj.locality);
                      NSLog(@"subLocality=%@", addressObj.subLocality);
                      NSLog(@"administrativeArea=%@", addressObj.administrativeArea);
                      NSLog(@"postalCode=%@", addressObj.postalCode);
                      NSLog(@"country=%@", addressObj.country);
                      NSLog(@"lines=%@", addressObj.lines);
                  }
              }];
      

      【讨论】:

      • 您可以只输出地址对象本身而不是所有单个字段 - 对象通过其描述属性很好地格式化为字符串 - NSLog(@"%@", addressObj);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多