Если у Вас есть io.popen, то это - то, что я использую:
function os.capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+, Если у Вас нет io.popen, тогда по-видимому, popen (3), не доступно в Вашей системе, и Вы находитесь в глубоком йогурте. Но все порты Lua Unix/Mac/окон будут иметь io.popen.
, '') s = string.gsub(s, '[\n\r]+', ' ') return s end
, Если у Вас нет io.popen, тогда по-видимому, popen (3), не доступно в Вашей системе, и Вы находитесь в глубоком йогурте. Но все порты Lua Unix/Mac/окон будут иметь io.popen.
Вот обновленная, более компактная версия кода unforgiven, которая использует последнюю версию API v3:
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
double latitude = 0, longitude = 0;
NSString *esc_addr = [address 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;
center.latitude = latitude;
center.longitude = longitude;
return center;
}
Она делает предположение, что координаты для "location" идут первыми, например, перед координатами для "viewport", потому что она просто берет первые найденные координаты под ключами "lng" и "lat". Не стесняйтесь использовать правильный сканер JSON (например, SBJSON), если вас беспокоит эта простая техника сканирования, использованная здесь.
Для этого вы можете использовать Google Geocoding . Это так же просто, как получить данные через HTTP и проанализировать их (он может возвращать JSON KML, XML, CSV).
The following method does what you asked for. You need to insert your Google maps key for this to work correctly.
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{
int code = -1;
int accuracy = -1;
float latitude = 0.0f;
float longitude = 0.0f;
CLLocationCoordinate2D center;
// setup maps api key
NSString * MAPS_API_KEY = @"YOUR GOOGLE MAPS KEY HERE";
NSString *escaped_address = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
// Contact Google and make a geocoding request
NSString *requestString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv&oe=utf8&key=%@&sensor=false&gl=it", escaped_address, MAPS_API_KEY];
NSURL *url = [NSURL URLWithString:requestString];
NSString *result = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error:NULL];
if(result){
// we got a result from the server, now parse it
NSScanner *scanner = [NSScanner scannerWithString:result];
[scanner scanInt:&code];
if(code == 200){
// everything went off smoothly
[scanner scanString:@"," intoString:nil];
[scanner scanInt:&accuracy];
//NSLog(@"Accuracy: %d", accuracy);
[scanner scanString:@"," intoString:nil];
[scanner scanFloat:&latitude];
[scanner scanString:@"," intoString:nil];
[scanner scanFloat:&longitude];
center.latitude = latitude;
center.longitude = longitude;
return center;
}
else{
// the server answer was not the one we expected
UIAlertView *alert = [[[UIAlertView alloc]
initWithTitle: @"Warning"
message:@"Connection to Google Maps failed"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil] autorelease];
[alert show];
center.latitude = 0.0f;
center.longitude = 0.0f;
return center;
}
}
else{
// no result back from the server
UIAlertView *alert = [[[UIAlertView alloc]
initWithTitle: @"Warning"
message:@"Connection to Google Maps failed"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil] autorelease];
[alert show];
center.latitude = 0.0f;
center.longitude = 0.0f;
return center;
}
}
center.latitude = 0.0f;
center.longitude = 0.0f;
return center;
}
Также есть CoreGeoLocation, который завершает функциональность во фреймворке (Mac) или статической библиотеке (iPhone). Поддерживает поиск через Google или Yahoo, если вы предпочитаете одно другому.
Для ключевого решения карты Google, как описано выше, не нужно делать приложение бесплатным? В соответствии с условиями и положениями Google: 9.1 Бесплатная, общедоступная реализация вашей API Карт. Ваша реализация API Карт должна быть общедоступной для пользователей бесплатно.
С набором карт в SDK 3.0 это легко сделать с помощью SDK. См. Руководства Apple или следуйте: https://developer.apple.com/documentation/mapkit