如何从城市名称中找到经纬度 [英] How to find the lat long from a city name
问题描述
我有一个城市名称,但没有该城市的经纬度值。我该如何从城市名称中获取经度和纬度值,然后将其保存到iOS中的变量中?我已经看过反向地理编码,但是看过的示例却与我所寻找的相反(他们从经纬度中找到城市名称)。
I have a city name but not the lat long values for that city. How would I go about getting the lat and long values from a city name and then save it to a variable in iOS? I've seen the geo reverse coding but the examples I've seen do the opposite to what I'm looking for (they find the city name from the lat/lon).
推荐答案
创建一个地址解析器并传递字符串名称:
Create a geocoder and pass in the string name:
请确保将CoreLocation添加到您的项目中,并添加 #import< CoreLocation / CoreLocation.h>
,或者,如果您使用的是Xcode 5,模块支持将使用 @import CoreLocation自动链接到正确的框架;
Be sure to add CoreLocation to your project and #import <CoreLocation/CoreLocation.h>
, alternatively, if you are using Xcode 5, module support will automatically link against the correct framework with @import CoreLocation;
NSString *city = @"New York, New York";
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder geocodeAddressString:city completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
return; // Bail!
}
if ([placemarks count] > 0) {
CLPlacemark *placemark = [placemarks lastObject]; // firstObject is iOS7 only.
NSLog(@"Location is: %@", placemark.location);
}
}];
这给出了
位置是:< + 40.72377900,-73.99128900> +/- 100.00m(速度-1.00 mps /路线-1.00)@ 9/24/13,2:34:18 PM英国夏令时
Location is: <+40.72377900,-73.99128900> +/- 100.00m (speed -1.00 mps / course -1.00) @ 9/24/13, 2:34:18 PM British Summer Time
我只是在记录地标,所以您可以得到更多,但是您可以在那看到纽约很长的纬度。
I'm just logging the placemark so you get a bit more, but you can see the lat, long of New York in there.
这篇关于如何从城市名称中找到经纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!