【发布时间】:2010-05-13 12:07:19
【问题描述】:
我有一个 iPhone 应用程序,我需要在其中找出当前位置(根据城市名称或可能是地址)。但我无法做到这一点。我可以找出当前的纬度和经度。如果我提供纬度和经度,是否有任何网络服务(最好是免费的)可以返回当前位置名称?
【问题讨论】:
标签: iphone geolocation reverse-geocoding
我有一个 iPhone 应用程序,我需要在其中找出当前位置(根据城市名称或可能是地址)。但我无法做到这一点。我可以找出当前的纬度和经度。如果我提供纬度和经度,是否有任何网络服务(最好是免费的)可以返回当前位置名称?
【问题讨论】:
标签: iphone geolocation reverse-geocoding
您要查找的功能称为Reverse Geocoding。
Here 是提供此功能的 Web 服务列表。
最流行的几个是 Geonames.org、Google Maps Services API 和 Batchgeo.com,用于批量处理多个坐标。
【讨论】:
假设您的目标是 iPhone OS 3.0 或更高版本,您可以使用 MKReverseGeocoder,它是 MapKit 框架的一部分。开发者文档包括一个示例项目。 MKReverserGeocoder Class Reference
【讨论】:
MKReverseGeocoder 是一个很棒的类,但有时可能会返回错误: Error Domain=PBRequesterErrorDomain Code=6001 "操作无法完成。(PBRequesterErrorDomain 错误6001。)
luvieere 的上述建议是一个很好的起点,这就是我使用 Google HTTP 反向地理编码器作为示例所做的。这是我编写的 GoogleReverseGeocoder 类的实现。使用方法的完整说明可以在HERE找到。
// Send Google A Request
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%lf,%lf&output=csv&sensor=false",self.locationToGeocode.coordinate.latitude,self.locationToGeocode.coordinate.longitude];
NSURL *urlFromString = [NSURL URLWithString:urlString];
NSStringEncoding encodingType = NSUTF8StringEncoding;
NSString *reverseGeoString = [NSString stringWithContentsOfURL:urlFromString encoding:encodingType error:nil];
// Parse Out Response
NSArray *listItems = [reverseGeoString componentsSeparatedByString:@","];
NSArray *tempAddressArray = [[listItems objectAtIndex:2] componentsSeparatedByString:@"\""];
NSArray *tempCountryArray = [[listItems objectAtIndex:[listItems count]-1] componentsSeparatedByString:@"\""];
// Did Google Find Address? 200 is yes
if ([[listItems objectAtIndex:0] intValue] == 200)
{
// Set Class Member Variables
[self setGoogleReturnDidFindAddress:YES];
[self setGoogleReturnAddress:[tempAddressArray objectAtIndex:[tempAddressArray count]-1]];
[self setGoogleReturnCountry:[tempCountryArray objectAtIndex:0]];
[self setGoogleReturnCode:[[listItems objectAtIndex:0] intValue]];
[self setGoogleReturnAccuracy:[[listItems objectAtIndex:1] intValue]];
} else if ([[listItems objectAtIndex:0] intValue] > 600)
{
[self setGoogleReturnDidFindAddress:NO];
}
【讨论】:
想自己做吗?
您必须为这些服务中的大部分付费,但有上千个限制。也许您可以拥有自己的州和城市列表,以及它们已知的纬度和经度。
不要尝试自己构建列表。例如,这个项目是巴西的州和城市数据库:
https://github.com/kelvins/Municipios-Brasileiros
5.570 个城市的列表只有 430KBytes!考虑到您必须存储的数据量以及从中获得的好处,这完全值得。
因此,最好的方法是从您所在的国家/地区找到一个类似的项目并实现它。
现在我有了自己的城市列表,我可以为用户获取最近的 5 个城市,或者做任何我想做的事情。通过这个对我的应用程序 MySQL 数据库的简单查询!看看多么简单而强大
set @lat=-20.0080509185791;
set @lng=-44.003021240234375;
-- The main SQL query that returns the closest 5 airports.
SELECT id, nome, lat, lng, 111.045 * DEGREES(ACOS(COS(RADIANS(@lat))
* COS(RADIANS(lat))
* COS(RADIANS(lng) - RADIANS(@lng))
+ SIN(RADIANS(@lat))
* SIN(RADIANS(lat))))
AS distance_in_km
FROM cities
ORDER BY distance_in_km ASC
LIMIT 0,5;
【讨论】: