iPhone - 从Latitude和Longtiude获取城市名称 [英] iPhone - Get City name from Latitude and Longtiude

查看:114
本文介绍了iPhone - 从Latitude和Longtiude获取城市名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



目前我正在使用CLLocationManager获取经度和纬度,并且我将我的坐标传递给CLGeocoder 。

  CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; 
[geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray * placemarks,NSError * error){
for(CLPlacemark * placemark in placemarks){
UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @当前城市消息:[NSString stringWithFormat:@Your Current City:%@,[placemark locality]] delegate:self cancelButtonTitle:@OKotherButtonTitles:@Cancel,nil];
[alert show];
}
}];

这适用于iOS 5.0,但不适用于iOS 4.3。 b

另外,我开始使用Google Web服务

   - (void)findLocationFor :( NSString *)latitudeStr 
andLontitude:(NSString *)longtitudeStr {
if([self connectedToWiFi]){
float latitude = [latitudeStr floatValue];
float longitude = [longtitudeStr floatValue];
NSMutableDictionary *参数= [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@%f,%f,latitude,longitude],@latlng,nil];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@http://maps.googleapis.com/maps/api/geocode/json]];
[参数setValue:@trueforKey:@sensor];
[参数setValue:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] forKey:@language];
NSMutableArray * paramStringsArray = [NSMutableArray arrayWithCapacity:[[parameters allKeys] count]];

for(NSString * key in [parameters allKeys]){
NSObject * paramValue = [parameters valueForKey:key];
[paramStringsArray addObject:[NSString stringWithFormat:@%@ =%@,key,paramValue]];
}

NSString * paramsString = [paramStringsArray componentsJoinedByString:@&];
NSString * baseAddress = request.URL.absoluteString;
baseAddress = [baseAddress stringByAppendingFormat:@?%@,paramsString];
[request setURL:[NSURL URLWithString:baseAddress]];

NSError * error = nil;
NSURLResponse * response = nil;
NSData * returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:& response error:& error];
if(response == nil){
if(error!= nil){
}
}
else {
NSDictionary * responseDict = [returnData objectFromJSONData];
NSArray * resultsArray = [responseDict valueForKey:@results];
NSMutableArray * placemarksArray = [NSMutableArray arrayWithCapacity:[resultsArray count]];
for(NSDictionary * placemarkDict in resultsArray){
NSDictionary * coordinateDict = [[placemarkDict valueForKey:@geometry] valueForKey:@location];

float lat = [[coordinateDict valueForKey:@lat] floatValue];
float lng = [[coordinateDict valueForKey:@lng] floatValue];

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@%。f,lat] forKey:@latitude];
[dict setObject:[NSString stringWithFormat:@%。f,lng] forKey:@longitude];
[dict setObject:[placemarkDict objectForKey:@formatted_address] forKey:@address];

[placemarksArray addObject:dict];
[词典释放];
}
NSDictionary * placemark = [placemarksArray objectAtIndex:0];
}
}
}

但是我的回复越来越长,意味着我仍然无法获得城市名称,因为在某些情况下,此Web服务会提供有关坐标的所有其他信息。期望城市名称。



任何一个请帮助我吗?

解决方案

根据文档 CLGeocoder 在iOS5下不起作用。你需要采取另一条路线来支持iOS4和iOS5。



你可以看看 MKReverseGeocoder ,但它在iOS5中已弃用,但仍可用于此目的。要进行确认,您可以查看所谓的问题

  +(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude 
{
NSString * urlString = [NSString stringWithFormat:@http: //maps.google.com/maps/geo?q=%f,%f&output=csv\",pdblLatitude,pdblLongitude];
NSError *错误;
NSString * locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:& error];
locationString = [locationString stringByReplacingOccurrencesOfString:@\withString:@];
return [locationString substringFromIndex:6];
}

你可以使用这个函数获取纬度和经度的地址,你可以根据需要改变它,我们把它作为Class方法,这样我们可以直接使用它作为

  NSString * strAddressFromLatLong = [CLassName getAddressFromLatLon:37.484848 withLongitude:74.48489]; 

编辑

请停止使用上述功能停止工作评论(未经测试)我建议开始使用 SVGeocoder


I want get my Current City name in my iPhone App.

I'm currently getting the latitude and longitude using CLLocationManager and than i am passing my coordinates into CLGeocoder.

    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Current City" message:[NSString stringWithFormat:@"Your Current City:%@",[placemark locality]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
            [alert  show];
        }  
    }];

This is working fine in iOS 5.0 but not working in iOS 4.3.

As an alternative, I started using the Google Web service

-(void)findLocationFor:(NSString *)latitudeStr 
          andLontitude:(NSString *)longtitudeStr{
    if ([self connectedToWiFi]){
        float latitude  = [latitudeStr floatValue];
        float longitude = [longtitudeStr floatValue];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
                                           [NSString stringWithFormat:@"%f,%f", latitude, longitude], @"latlng", nil];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/geocode/json"]];
        [parameters setValue:@"true" forKey:@"sensor"];
        [parameters setValue:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] forKey:@"language"];
        NSMutableArray *paramStringsArray = [NSMutableArray arrayWithCapacity:[[parameters allKeys] count]];

        for(NSString *key in [parameters allKeys]) {
            NSObject *paramValue = [parameters valueForKey:key];
            [paramStringsArray addObject:[NSString stringWithFormat:@"%@=%@", key, paramValue]];
        }

        NSString *paramsString = [paramStringsArray componentsJoinedByString:@"&"];
        NSString *baseAddress = request.URL.absoluteString;
        baseAddress = [baseAddress stringByAppendingFormat:@"?%@", paramsString];
        [request setURL:[NSURL URLWithString:baseAddress]];

        NSError        *error    = nil;
        NSURLResponse  *response = nil;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if (response == nil) {
            if (error != nil) {
            }
        }
        else {
            NSDictionary *responseDict = [returnData objectFromJSONData];
            NSArray *resultsArray = [responseDict valueForKey:@"results"]; 
            NSMutableArray *placemarksArray = [NSMutableArray arrayWithCapacity:[resultsArray count]];
            for(NSDictionary *placemarkDict in resultsArray){
                NSDictionary *coordinateDict = [[placemarkDict valueForKey:@"geometry"] valueForKey:@"location"];

                float lat = [[coordinateDict valueForKey:@"lat"] floatValue];
                float lng = [[coordinateDict valueForKey:@"lng"] floatValue];

                NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                [dict setObject:[NSString stringWithFormat:@"%.f",lat] forKey:@"latitude"];
                [dict setObject:[NSString stringWithFormat:@"%.f",lng] forKey:@"longitude"];
                [dict setObject:[placemarkDict objectForKey:@"formatted_address"] forKey:@"address"];

                [placemarksArray addObject:dict];
                [dict release];
            }
            NSDictionary *placemark = [placemarksArray objectAtIndex:0];
        }
    }
}

But the response which i am getting is too long , means i am still unable to get the city name because in some case this web service give all other information regarding coordinates expect City Name.

Can any one help me please?

解决方案

As per documentation CLGeocoder does not work below iOS5. You need to take another route to support iOS4 and iOS5 both.

You can look at MKReverseGeocoder, however it is deprecated in iOS5 but still will serve the purpose. For confirmation you can check so called question

+(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude
{
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pdblLatitude, pdblLongitude];
    NSError* error;
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
    locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    return [locationString substringFromIndex:6];
}

You can use this function for getting address from latitude, longitude. You can change according to requirement. We put this as Class method so we can directly use it as

NSString *strAddressFromLatLong = [CLassName getAddressFromLatLon:37.484848 withLongitude:74.48489];

EDIT

Please stop using above function as it has stopped working reported in comments (Not tested by me). I recommend to start using SVGeocoder

这篇关于iPhone - 从Latitude和Longtiude获取城市名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆