问题
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).
回答1:
Create a geocoder and pass in the string name:
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);
}
}];
which gives
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.
来源:https://stackoverflow.com/questions/18982535/how-to-find-the-lat-long-from-a-city-name