如何从iOS中输入的文本中查找位置

时间:2014-03-06 07:40:38

标签: ios google-maps

我正在使用iOS上的Google地图。我想根据我输入的文本(地址)搜索位置。那么,我怎样才能找到位置(纬度和经度) 从输入的文字?

3 个答案:

答案 0 :(得分:2)

以下是从地址

获取坐标的代码
- (void)geocodeFromAddress:(NSString *)address {
    //6
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        if([placemarks count]) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            CLLocation *location = placemark.location;
            CLLocationCoordinate2D coordinate = location.coordinate;
            NSLog(@"coordinate = (%f, %f)", coordinate.latitude, coordinate.longitude);
        } else {
            NSLog(@"error");
        }
    }];
}

答案 1 :(得分:1)

请使用此方法,将地址作为参数传递,并返回具有所需纬度和经度的CLLocation2D对象。

+(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;
     GMSCameraUpdate *updatedCamera = [GMSCameraUpdate setTarget:center zoom:19.1];
    [_Map animateWithCameraUpdate:updatedCamera];
    marker.position=center;

}

答案 2 :(得分:0)

GLGeocoder将完成这项工作!

尝试调整此代码...

NSDictionary *locationDictionary = **SET ADDRESS HERE**;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressDictionary:locationDictionary completionHandler:^(NSArray *placemarks, NSError *error)
     {   
         if(!error){
             CLPlacemark *placemark = [placemarks objectAtIndex:0]; //only take the 1st found
             self.latitudeTextField.value = placemark.location.coordinate.latitude;
             self.longitudeTextField.value = placemark.location.coordinate.longitude;
         }
         else{
             // Our geocoder had an error, output a message
            self.result.text = [NSString stringWithFormat:NSLocalizedString (@"There was a forward geocoding error\n%@", @"Geocoder"), [error localizedDescription]];
         }
     }];