iPhone-从Latitude和Longtude获取城市名称
我想在我的iPhone应用程序中获取我当前的城市名称 我目前正在使用CLLocationManager获取纬度和经度,然后将坐标传递给CLGeocoderiPhone-从Latitude和Longtude获取城市名称,iphone,objective-c,ios,google-maps,Iphone,Objective C,Ios,Google Maps,我想在我的iPhone应用程序中获取我当前的城市名称 我目前正在使用CLLocationManager获取纬度和经度,然后将坐标传递给CLGeocoder CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { for
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];
}
}];
import @corelocation and for getting city,country #import <AddressBook/AddressBook.h>
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location=[locations lastObject];
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
CLLocationCoordinate2D coord;
coord.longitude = location.coordinate.longitude;
coord.latitude = location.coordinate.latitude;
// or a one shot fill
coord = [location coordinate];
NSLog(@"longitude value%f", coord.longitude);
NSLog(@"latitude value%f", coord.latitude);
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = [placemark addressDictionary];
city = addressDictionary[(NSString *)kABPersonAddressCityKey];
stateloc = addressDictionary[(NSString *)kABPersonAddressStateKey];
country = placemark.country;
NSLog(@"city%@/state%@/country%@",city,stateloc,country);
[self getImagesFromServer:city];
}];
[self stopSignificantChangesUpdates];
}
- (void)stopSignificantChangesUpdates
{
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
}
这在iOS 5.0中运行良好,但在iOS 4.3中不起作用
作为替代,我开始使用Google Web服务
-(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];
}
}
}
但是,我得到的响应太长,这意味着我仍然无法获取城市名称,因为在某些情况下,此web服务会提供除城市名称之外的所有其他信息
有人能帮我吗?根据文档,iOS5下不起作用。您需要采取另一种方式来同时支持iOS4和iOS5
您可以看到,尽管它在iOS5中已被弃用,但仍然可以发挥作用。如需确认,您可以查看
您可以使用此函数从纬度、经度获取地址。您可以根据需要更改。我们把它作为类方法,这样我们就可以直接使用它作为类方法
NSString *strAddressFromLatLong = [CLassName getAddressFromLatLon:37.484848 withLongitude:74.48489];
编辑
请停止使用上述功能,因为它已停止工作,并在评论中报告(我未测试)。我建议开始使用
对不起,我的英语不好,希望它能帮助你我找到了这段代码,它对我有用:
只需将
placemark.ISOcountryCode
更改为placemark.locality
我正在使用它并获取邮政编码和城市名称。修改了Janak添加的方法
- (void)reverseGeocode:(CLLocation *)location {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Finding address");
if (error) {
NSLog(@"Error %@", error.description);
} else {
CLPlacemark *placemark = [placemarks lastObject];
self.myAddress.text = [NSString stringWithFormat:@"%@", ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO)];
}
}];
}
- (void) getAddressFromLatLon:(CLLocation *)bestLocation
{
NSLog(@"%f %f", bestLocation.coordinate.latitude, bestLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:bestLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);
NSLog(@"locality %@",placemark.locality);
NSLog(@"postalCode %@",placemark.postalCode);
}];
}
在此处尝试此请求,您将找到有关当前位置、街道/城市/地区名称、门牌号的所有数据,但对于您的请求,只需粘贴此数据即可
NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",pdblLatitude, pdblLongitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:kResults] objectAtIndex:0];
NSString *cityName = [[[dic objectForKey:@"address_components"] objectAtIndex:1] objectForKey:@"long_name"];
这很好,对我有用 我使用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:@"Current City" message:[NSString stringWithFormat:@"Your Current City:%@",[placemark locality]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
[alert show];
}
}];
import @corelocation and for getting city,country #import <AddressBook/AddressBook.h>
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location=[locations lastObject];
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
CLLocationCoordinate2D coord;
coord.longitude = location.coordinate.longitude;
coord.latitude = location.coordinate.latitude;
// or a one shot fill
coord = [location coordinate];
NSLog(@"longitude value%f", coord.longitude);
NSLog(@"latitude value%f", coord.latitude);
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = [placemark addressDictionary];
city = addressDictionary[(NSString *)kABPersonAddressCityKey];
stateloc = addressDictionary[(NSString *)kABPersonAddressStateKey];
country = placemark.country;
NSLog(@"city%@/state%@/country%@",city,stateloc,country);
[self getImagesFromServer:city];
}];
[self stopSignificantChangesUpdates];
}
- (void)stopSignificantChangesUpdates
{
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
}
import@corelocation和获取城市、国家/地区的导入
-(无效)位置管理器:(CLLocationManager*)管理器更新位置:(NSArray*)位置
{
CLLocation*location=[locations lastObject];
CLGeocoder*geocoder=[[CLGeocoder alloc]init];
CLLocationCoordinate2D coord;
坐标经度=位置坐标经度;
坐标纬度=位置坐标纬度;
//还是一次灌满
坐标=[位置坐标];
NSLog(@“经度值%f”,坐标经度);
NSLog(@“纬度值%f”,坐标纬度);
[geocoder reverseGeocodeLocation:位置完成处理程序:^(NSArray*位置标记,NSError*错误){
CLPlacemark*placemark=placemarks[0];
NSDictionary*addressDictionary=[placemark addressDictionary];
city=地址字典[(NSString*)KabPersonalAddressCityKey];
stateloc=addressDictionary[(NSString*)KabPersonalAddressStateKey];
country=placemark.country;
NSLog(@“城市%@/州%@/国家%@”,城市,州,国家);
[self-getImagesFromServer:city];
}];
[自停止重大变更日期];
}
-(作废)停止重大变更日期
{
[self.locationManager停止更新位置];
self.locationManager=nil;
}
我改进了@Constantin Saulenco伟大的答案-
json导致不总是按相同的顺序排序-因此城市不总是在相同的索引中-此func将搜索正确的索引。
另外还有一个国家
NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:@"results"] objectAtIndex:0];
NSArray* arr = [dic objectForKey:@"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
NSString *countryName;
for (NSDictionary* d in arr)
{
NSArray* typesArr = [d objectForKey:@"types"];
NSString* firstType = [typesArr objectAtIndex:0];
if([firstType isEqualToString:@"locality"])
cityName = [d objectForKey:@"long_name"];
if([firstType isEqualToString:@"country"])
countryName = [d objectForKey:@"long_name"];
}
NSString* locationFinal = [NSString stringWithFormat:@"%@,%@",cityName,countryName];
它对我有用:)
请检查下面的功能
func getDataCity(tmpLat:Double,tmpLong:Double) {
let tmpCLGeocoder = CLGeocoder.init()
if tmpLat > 0 , tmpLong > 0
{
let tmpDataLoc = CLLocation.init(latitude: tmpLat, longitude: tmpLong)
tmpCLGeocoder.reverseGeocodeLocation(tmpDataLoc, completionHandler: {(placemarks,error) in
guard let tmpPlacemarks = placemarks else{
return
}
let placeMark = tmpPlacemarks[0] as CLPlacemark
guard let strLocality = placeMark.locality else{
return
}
// strLocality is your city
guard let strSubLocality = placeMark.subLocality else{
return
}
// strSubLocality is your are of city
})
}
}
有时此代码不起作用,请尝试寻找其他解决方案不适用于我我使用此输出为“610,0,0,0”@HardikShah您之所以获得此输出,是因为您使用的是csv。将其更改为xml或json,如
output=xml
它将告诉您这是旧的地理编码,而新的则不同。您还将获得xml或json响应中的新地理编码链接。@Chandni您可以看到更新的注释,不要使用上面的函数,因为它已停止工作。检查该链接:它正在返回国家,因此代码不是泛化的,请检查。请参阅swift 4.1 Xcode 9.4.1中的我的答案。你甚至可以获得村庄名称的详细信息。
func getDataCity(tmpLat:Double,tmpLong:Double) {
let tmpCLGeocoder = CLGeocoder.init()
if tmpLat > 0 , tmpLong > 0
{
let tmpDataLoc = CLLocation.init(latitude: tmpLat, longitude: tmpLong)
tmpCLGeocoder.reverseGeocodeLocation(tmpDataLoc, completionHandler: {(placemarks,error) in
guard let tmpPlacemarks = placemarks else{
return
}
let placeMark = tmpPlacemarks[0] as CLPlacemark
guard let strLocality = placeMark.locality else{
return
}
// strLocality is your city
guard let strSubLocality = placeMark.subLocality else{
return
}
// strSubLocality is your are of city
})
}
}